2017-08-01 25 views
4

我想要一個全局對象來修改其自己的方法之一初始化的回調函數中的一個自己的變量。回調似乎有效,但在測試全局變量時,該變量似乎沒有被修改過。爲什麼這個對象中的變量沒有被其回調函數修改?

爲什麼全局對象沒有被修改?是否將全局對象的更改保存在某個暫存區域中,等待完成回調函數?

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

}); 
+5

的可能的複製[如何訪問正確的\'這\'回調裏面?](https://開頭stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) –

回答

3

的問題是,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); 
} 
+3

這對於箭頭函數也是一個很好的用例。不需要設置'self'變量 – mhodges

+1

是的,謝謝。我會將其添加到答案中 – qiAlex

相關問題