Why is the variable in this object not changed by the callback function?

I am trying to get a global object to change one of my variables in a callback function initialized by one of my own methods. The callback seems to work, but the variable does not seem to have been changed when testing the global variable.

Why does the global object not change? Are changes to the global object saved in any staging area until the callback function completes?

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);

});
+4
source share
1 answer

The problem is that it setTimeoutcreates its own this. The solution might look like 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);
}
+3

Source: https://habr.com/ru/post/1682771/


All Articles