我想在每次实例化一个类时在javascript中启动setInterval
方法(我知道,我不应该在javascript中将它称为类,...)。 setInterval
每500毫秒调用一次类方法update
。这是我的代码:
function Test(a) {
this.a = a;
this.b = 0;
this.interval = setInterval(this.update, 500);
};
Test.prototype.update = function() {
console.log(this.b);
this.b += 1;
if (this.b > 10) clearInterval(this.interval);
};
但是当我使用var mytest = new Test(1)
实例化类时,类属性b
似乎在第一次调用中未定义,随后是NaN(因为在undefined中添加1会给出NaN)。为什么第一次通话中b
不是0
?
答案 0 :(得分:2)
当setInterval触发时,this
的范围会发生变化。 this
将为window
。要维护范围,您可以使用bind。
setInterval(this.update.bind(this), 500);