Javascript 回调如何在两个类之间工作?

Javascript 回调如何在两个类之间工作?,javascript,callback,Javascript,Callback,我正在学习一门课程,试图了解回调在两个类之间是如何工作的。我准备了这个例子: 功能车(){ this.offer={}; this.OfferUpdate=()=>{ this.callback(this.offer) } this.callback=函数(){}; this.Listener=(回调)=>{ this.callback=回调; } } var car=新车(); car.offer={ 型号:['A4','A5','A6'], 引擎:['TDI','TFSI'] } 高级汽车

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

功能车(){
this.offer={};
this.OfferUpdate=()=>{
this.callback(this.offer)
}
this.callback=函数(){};
this.Listener=(回调)=>{
this.callback=回调;
}
}
var car=新车();
car.offer={
型号:['A4','A5','A6'],
引擎:['TDI','TFSI']
}
高级汽车陈列室{
构造函数(){
this.model=['A4'];
this.engine=['TDI'];
car.Listener((newItems)=>{
this.model=newItems.model
this.engine=newItems.engine
})
}
}
let car_展厅=新车展厅();
设p=document.createElement(“p”)
设p2=document.createElement(“p”)
让text=document.createTextNode(“car.offer:+JSON.stringify(car.offer));
让text2=document.createTextNode(“汽车展厅:+JSON.stringify(汽车展厅))
p、 附件(文本);
文件.正文.附件(p);
p2.追加子女(文本2);
文件.正文.附件(p2);
car.OfferUpdate()//运行回调
设p3=document.createElement(“p”)
让text3=document.createTextNode(“car.OfferUpdate()之后的car\u展厅:”+JSON.stringify(car\u展厅))
p3.追加儿童(text3);
文件.正文.附件(p3);
调用
this.callback(this.offer)
如何触发
listner()
方法

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

car.Listener((newItems) => {
    this.model = newItems.model
    this.engine = newItems.engine
})
car.Listener
执行以下操作:

this.callback = callback;
…将该函数引用保存在其
回调
属性中。这意味着该车的
回调
现在是对传递到
car.Listener
中的函数的引用(设置
模型
引擎
上面的箭头函数)。所以稍后,
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)

为什么你认为
Listener
会被启动,而不是之前传递到那里的回调?旁注:虽然你可以在自己的代码中做你喜欢做的事情,但JavaScript中压倒性的惯例是,只有构造函数是大写的,单词分隔使用的是camelCase而不是下划线。所以你的
汽车
很好,
汽车展厅
将是
汽车展厅
(或
汽车展厅
),
监听器
将是
监听器
提供更新
将是
提供更新
。。。在与他人共享代码时,如请求帮助时,遵守约定非常重要。:-)但无论如何这都是一个好主意。我知道在
this.callback
属性中保存对回调函数的引用,因此如果执行
this.callback(this.offer)
,那么也可以在
this.Listener
中使用referece运行方法?@JanuszO:不要挂断“reference”这个词任何时候,当您有一个函数的标识符时,它都是一个绑定(变量、参数、对象属性等),包含对函数的引用,因为函数是对象。就像
vara={};b=a
意味着我们有两种方式访问一个对象(通过
a
b
),
var a=function(){/*…*/};b=a
表示我们有两种引用该函数的方式(通过
a
和通过
b
)。由于JavaScript中的函数是对象,我们可以像对象一样传递它们。感谢您的帮助,我想了一点,我已经理解了;-)