我试图让一个全局对象在回调函数中修改它自己的变量之一,该回调函数由它自己的方法之一初始化。回调似乎有效,但在测试全局变量时变量似乎没有被修改。
为什么全局对象没有被修改?对全局对象的更改是否保留在某种等待回调函数完成的临时区域中?
let obj;
function test_object_flag() {
// 5 - check whether the "timer_finished" flag has been set
console.log("is the timer finished? " + obj.timer_finished); // should return "true"???
}
class TestClass {
constructor() {
this.timer_finished = false;
}
start_timer(ptr_callback_function) {
// 3 - set up a callback for the timer
setTimeout(function() {
// 4 - once the timer is done, set a "timer_finished" flag, and call the callback
this.timer_finished = true;
ptr_callback_function();
}, 1000);
}
}
$( document ).ready(function() {
// 1 - make a new onbject of type TestClass
obj = new TestClass();
// 2 - start the timer
obj.start_timer(test_object_flag);
});
最佳答案
问题是 setTimeout
创建了它自己的 this
。解决方案可能如下所示:
start_timer(ptr_callback_function) {
// savig this that your need
const self = this;
setTimeout(function() {
// use needed context
self.timer_finished = true;
ptr_callback_function();
}, 1000);
}
另一种选择是使用箭头函数:
start_timer(ptr_callback_function) {
setTimeout(() => {
this.timer_finished = true;
ptr_callback_function();
}, 1000);
}
关于javascript - 为什么这个对象中的变量没有被它的回调函数修改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45442016/