Javascript setInterval and `this` solution

2018-12-31 13:36发布

I need to access this from my setInterval handler

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

retrieve_rate : function()
    {
        var ajax = null;
        ajax = new XMLHttpRequest();
        ajax.open('GET', 'http://xyz.com', true);
        ajax.onload = function()
        {
            // access prefs here
        }
    }

How can I access this.prefs in ajax.onload ?

9条回答
君临天下
2楼-- · 2018-12-31 14:17
prefs: null,
startup : function()
    {
        // init prefs
        ...
        this.retrieve_rate();
        var context = this;
        this.intervalID = setInterval(function()
                                      {
                                          context.retrieve_rate();
                                      }, this.INTERVAL);
    },

retrieve_rate : function()
    {
        var ajax = null;
        ajax = new XMLHttpRequest();
        ajax.open('GET', 'http://xyz.com', true);
        var context = this;
        ajax.onload = function()
        {
            // access prefs using context.
            // e.g. context.prefs
        }
    }
查看更多
不再属于我。
3楼-- · 2018-12-31 14:20

window.setInterval(function(){console.log(this)}.bind(this), 100)

this is legal in javascript and saves lots of code :)

查看更多
泛滥B
4楼-- · 2018-12-31 14:21
this.intervalID = setInterval(this.retrieve_rate.bind(this), this.INTERVAL);
查看更多
登录 后发表回答