Javascript setInterval and `this` solution

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

    With improving browser support the time is now good to use the EcmaScript 6 enhancement, the arrow => method, to preserve this properly.

    startup : function()
        {
            // init prefs
            ...
            this.retrieve_rate();
            this.intervalID = setInterval( () => this.retrieve_rate(), this.INTERVAL);
        },
    

    Using => method preserves the this when retrieve_rate() is called by the interval. No need for funky self or passing this in parameters

提交回复
热议问题