如何通过在 javascript 中更新类对象的变量,方法是将回调传递给单独对象中的另一个函数



如何通过将回调传递给单独对象内的另一个函数来更新特定类对象的变量。在类 Example 的代码中,当我创建它的对象然后调用它的 callOtherMethod 控制台时.log由 updateArr() 方法制作,将 this.arr 显示为未定义。这是我面临的问题的一个例子。谢谢你的帮助

class Example{
constructor(){
this.arr = [];
this.index = 2;
}
updateArr(str){
this.arr[this.index] = str;
console.log(this.arr)
}
callOtherMethod(){
this.index = 1;
anotherObject.method(this.updateArr)
}
}
anotherObject= {
method : (callback) =>{
callback('Hello')
}
}
const ex = new Example();
ex.callOtherMethod()
//logs this.arr undefined

当您传递this.updateArr并在method函数中执行它时:

method : (callback) =>{
callback('Hello')
}

。绑定到updateArrthis将丢失,因为未指定对callback的调用上下文。

若要解决此问题,可以将this.updateArr的特殊版本传递给anotherObject.method()方法,该方法使用.bind()函数显式绑定其this.bind()方法将返回一个新函数,其中this绑定为您传递的第一个参数。

请参阅以下示例:

class Example {
constructor() {
this.arr = [];
this.index = 2;
}
updateArr(str) {
this.arr[this.index] = str;
console.log(this.arr)
}
callOtherMethod() {
this.index = 1;
// pass a function with the `this` being bound to the current object
anotherObject.method((...args) => this.updateArr(...args))
}
}
anotherObject = {
method: (callback) => {
callback('Hello')
}
}
const ex = new Example();
ex.callOtherMethod();

或者,您可以使用:

anotherObject.method((...args) => this.updateArr(...args))

这会将一个函数传递到arnotherObject.method()该函数在执行时将运行:

this.updateArr(...args)

由于此处的this引用对象实例(因为箭头函数没有自己的this绑定),因此您将能够调用实例的updateArr方法。

您可以使用将对象绑定到函数的传统方法,如另一个答案所示。

或者,将函数名称作为字符串与原始对象一起传递。然后使用对象的属性访问该函数:

class Example{
constructor(){
this.arr = [];
this.index = 2;
}
updateArr(str){
this.arr[this.index] = str;
console.log(this.arr)
}
callOtherMethod(){
this.index = 1;
anotherObject.method(this, "updateArr")
}
}
anotherObject= {
method : (obj, callback) =>{
obj[callback]('Hello');
}
}
const ex = new Example();
ex.callOtherMethod();

最新更新