在 Javascript 原型中使用计时器循环



以下内容不会循环:

function sequencer(){
    //empty for proof of concept
}
sequencer.prototype.start = function(){
    console.log("not looping");
    tid = setTimeout(this.start, 2000);
}
one = new sequencer();
one.start();

以下内容确实循环:

function start() {
    console.log("looping");
    tid = setTimeout(start, 2000); 
}
start();

为什么声明为类方法的函数的行为不同?

这是因为当调用 setTimeout 中的函数时,其上下文设置为 window 。 就像它被称为:

this.start.call(window)

因此,当再次调用start()时,this window,并且由于window.start不存在,因此它不会再次运行。

你可以这样尝试:

setTimeout(this.start.bind(this), 2000);

第二次调用时,this不是序列器实例,而是窗口对象。 创建一个简单的闭包来捕获this

function sequencer(){
    //empty for proof of concept
}
sequencer.prototype.start = function(){
    var that = this;
    console.log("not looping");
    setTimeout(function(){that.start()}, 2000);
}
var one = new sequencer();
one.start();

JS小提琴:http://jsfiddle.net/F4HgD/

最新更新