JavaScript setInterval 和 ‘this’ 的解决方案

By default, setInterval中的this 是被绑定到global context, 如果你想绑定到current context, 有如下几种解决方案:

(本文来自于stackoverflow: https://stackoverflow.com/questions/2749244/javascript-setinterval-and-this-solution)

Code:

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

如果我们想在setInterval里面access this,可以:

  1. 使用.bind
this.intervalID = setInterval(this.retrieve_rate.bind(this), this.INTERVAL);

2. 在函数外,把this 赋值给其他变量,常见是that 和 self

var self = this;
this.intervalID = setInterval(
function() { self.retrieve_rate(); },
this.INTERVAL);

3. 使用arrow function, 箭头函数

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.