Javascript setInterval and `this` solution

前端 未结 9 2027
花落未央
花落未央 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: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);
    

提交回复
热议问题