从相同 class 的另一个函数调用 class 的函数
Call a function of a class from another function of same class
class Frame {
constructor() {
this.init();
}
init(){
setTimeout(function(){this.secondFunction()}, 2000); // DOES NOT WORK
}
secondFunction(){
}
}
我正在尝试从 class 的另一个函数调用 class 的函数。当我直接用 "this.secondFunction()" 调用它时,它工作正常。但是当我将它移动到 setTimeout 或 JQuery 函数的内部时,它不起作用并抛出错误 "this.secondFunction is not a function"。我认为这是因为当我从 setTimeout 调用它时 "this" 更改为计时器对象。在这种情况下调用函数的正确方法是什么?
setTimeout
函数中的 this
不是您想要的。使用箭头函数:
setTimeout(() => {
this.secondFunction();
}, 2000);
问题是 setTimeout
中的函数正在将 this
引用从新实例更改为 setTimeout
,这不是您想要的。箭头函数继承了它的 this
绑定,所以它会完美地工作。
ES5 等效项是在回调之外使用 bind
来更改绑定。
setTimeout(function() {
this.secondFunction();
}.bind(this), 2000);
class Frame {
constructor() {
this.init();
}
init(){
setTimeout(function(){this.secondFunction()}, 2000); // DOES NOT WORK
}
secondFunction(){
}
}
我正在尝试从 class 的另一个函数调用 class 的函数。当我直接用 "this.secondFunction()" 调用它时,它工作正常。但是当我将它移动到 setTimeout 或 JQuery 函数的内部时,它不起作用并抛出错误 "this.secondFunction is not a function"。我认为这是因为当我从 setTimeout 调用它时 "this" 更改为计时器对象。在这种情况下调用函数的正确方法是什么?
setTimeout
函数中的 this
不是您想要的。使用箭头函数:
setTimeout(() => {
this.secondFunction();
}, 2000);
问题是 setTimeout
中的函数正在将 this
引用从新实例更改为 setTimeout
,这不是您想要的。箭头函数继承了它的 this
绑定,所以它会完美地工作。
ES5 等效项是在回调之外使用 bind
来更改绑定。
setTimeout(function() {
this.secondFunction();
}.bind(this), 2000);