Javascript setInterval and `this` solution

前端 未结 9 2062
花落未央
花落未央 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:07

    The setInterval line should look like this:-

     this.intervalID = setInterval(
         (function(self) {         //Self-executing func which takes 'this' as self
             return function() {   //Return a function in the context of 'self'
                 self.retrieve_rate(); //Thing you wanted to run as non-window 'this'
             }
         })(this),
         this.INTERVAL     //normal interval, 'this' scope not impacted here.
     ); 
    

    Edit: The same principle applies to the " onload ". In this case its common for the "outer" code to do little, it just sets up the request an then sends it. In this case the extra overhead an additinal function as in the above code is unnecessary. Your retrieve_rate should look more like this:-

    retrieve_rate : function()
    {
        var self = this;
        var ajax = new XMLHttpRequest();
        ajax.open('GET', 'http://xyz.com', true);
        ajax.onreadystatechanged= function()
        {
            if (ajax.readyState == 4 && ajax.status == 200)
            {
                // prefs available as self.prefs
            }
        }
        ajax.send(null);
    }
    

提交回复
热议问题