两个类之间如何回调?

时间:2017-11-09 12:29:53

标签: javascript callback

我正在做一个课程,并试图了解两个类之间的回调是如何工作的。我准备了这个例子:

    function Car() {

        this.offer = {};

        this.OfferUpdate = () => {
            this.callback(this.offer)
        }

        this.callback = function(){};

        this.Listener = (callback) => {
            this.callback = callback;
        }
    }

    var car = new Car();
    car.offer = {
        model: ['A4', 'A5', 'A6'],
        engine: ['TDI', 'TFSI']
    }

    class Car_showroom {

        constructor() {
            this.model = ['A4'];
            this.engine = ['TDI'];
 
            car.Listener((newItems) => {
                this.model = newItems.model
                this.engine = newItems.engine
            })
        }
    }

let car_showroom = new Car_showroom();
    
let p = document.createElement("p")
let p2 = document.createElement("p")
let text = document.createTextNode("car.offer: " + JSON.stringify(car.offer));
let text2 = document.createTextNode("car_showroom: " + JSON.stringify(car_showroom))
p.appendChild(text);
document.body.appendChild(p);
p2.appendChild(text2);
document.body.appendChild(p2);

car.OfferUpdate(); //run callback

let p3 = document.createElement("p")
let text3 = document.createTextNode("car_showroom after  car.OfferUpdate(): " + JSON.stringify(car_showroom))
p3.appendChild(text3);
document.body.appendChild(p3);
    

启动car.OfferUpdate()调用时,会启动此方法中的回调,启动listner()方法,但我不明白如何。

如何调用this.callback(this.offer)触发listner()方法?

1 个答案:

答案 0 :(得分:1)

  

如何调用this.callback(this.offer)触发listner()方法?

此代码调用car.Listener,将函数传递给它:

car.Listener((newItems) => {
    this.model = newItems.model
    this.engine = newItems.engine
})

car.Listener这样做:

this.callback = callback;

...在callback属性中保存该函数引用。这意味着该汽车的callback现在是对传递到car.Listener的函数的引用(设置modelengine上方的箭头函数)。所以稍后,this.callback(...)会调用箭头函数(不是Listener)。

可能有助于区分我们传入的函数和对car.Listener的调用更清楚。这段代码:

car.Listener((newItems) => {
    this.model = newItems.model
    this.engine = newItems.engine
})

可以像这样重写,以使区别更清晰:

// Create a callback we can give to `car`
const ourCallback = (newItems) => {
    this.model = newItems.model
    this.engine = newItems.engine
};
// Give that callback to `car`
car.Listener(ourCallback)