Javascript 为什么不是';对象中的变量是否被其回调函数修改?
我试图让一个全局对象在一个回调函数中修改它自己的变量,这个回调函数由它自己的方法初始化。回调似乎有效,但在测试全局变量时,该变量似乎没有被修改 为什么不修改全局对象?在回调函数完成之前,全局对象的更改是否保存在某种暂存区域中Javascript 为什么不是';对象中的变量是否被其回调函数修改?,javascript,jquery,callback,Javascript,Jquery,Callback,我试图让一个全局对象在一个回调函数中修改它自己的变量,这个回调函数由它自己的方法初始化。回调似乎有效,但在测试全局变量时,该变量似乎没有被修改 为什么不修改全局对象?在回调函数完成之前,全局对象的更改是否保存在某种暂存区域中 let obj; function test_object_flag() { // 5 - check whether the "timer_finished" flag has been set console.log("is the timer fi
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
创建了它自己的这个
。解决方案可能如下所示:
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);
}
对于箭头函数来说,这可能是一个很好的用例。无需设置
self
变量