Javascript setInterval and `this` solution

前端 未结 9 1936
花落未央
花落未央 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:20
    this.intervalID = setInterval(this.retrieve_rate.bind(this), this.INTERVAL);
    
    0 讨论(0)
  • 2020-11-22 09:21

    This would be the cleanest solution, since most of the time you actually want to switch the this context for your consecutive method calls:

    Also it's easier to grasp the concept of.

        // store scope reference for our delegating method
        var that = this;
        setInterval(function() {
            // this would be changed here because of method scope, 
            // but we still have a reference to that
            OURMETHODNAME.call(that);
        }, 200);
    
    0 讨论(0)
  • 2020-11-22 09:26

    That's not a beauty solution but it's in common usage:

    var self = this;
    var ajax = null;
    //...
    ajax.onload = function() {
        self.prefs....;
    }
    
    0 讨论(0)
提交回复
热议问题