我想要一個全局對象來修改其自己的方法之一初始化的回調函數中的一個自己的變量。回調似乎有效,但在測試全局變量時,該變量似乎沒有被修改過。爲什麼這個對象中的變量沒有被其回調函數修改?
爲什麼全局對象沒有被修改?是否將全局對象的更改保存在某個暫存區域中,等待完成回調函數?
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);
});
的可能的複製[如何訪問正確的\'這\'回調裏面?](https://開頭stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) –