javascript - 为什么这个对象中的变量没有被它的回调函数修改?

标签 javascript jquery callback

我试图让一个全局对象在回调函数中修改它自己的变量之一,该回调函数由它自己的方法之一初始化。回调似乎有效,但在测试全局变量时变量似乎没有被修改。

为什么全局对象没有被修改?对全局对象的更改是否保留在某种等待回调函数完成的临时区域中?

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/

相关文章:

python - 如何制作一个用CFFI包裹的C-DLL来回调python

javascript - Angular Promise 和两种方法

javascript - 将函数作为回调传递时的原型(prototype)问题

Javascript - 计算当前日期 1 年/3 个月/1 个月前的日期 (dd-mm-yyyy)

javascript - 不工作 Jquery 输入键和 Shift-Enter 键

javascript - 何时/为何在回调函数中使用 "return"

javascript - HTML5/JS 选择合适音频源的简单方法是什么?

php - 网站图标定制或动画

jquery - spring mvc中使用@PathVariable时ajax不起作用

C++ dll 的 C# 包装器; "Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call."错误