Javascript setInterval and `this` solution

前端 未结 9 2059
花落未央
花落未央 2020-11-22 08:44

I need to access this from my setInterval handler

prefs: null,
startup : function()
    {
        // init prefs
        ...
                


        
9条回答
  •  无人共我
    2020-11-22 09:11

    The default behavior of setInterval is to bind to the global context. You can call a member function by saving a copy of the current context. Inside retrieve_rate the this variable will be correctly bound to the original context. Here is what your code would look like:

    var self = this;
    this.intervalID = setInterval(
        function() { self.retrieve_rate(); },
        this.INTERVAL);
    

    Bonus tip: For a plain function reference (as opposed to an object reference which has a member function) you can change the context by using JavaScript's call or apply methods.

提交回复
热议问题