具有自执行功能的setTimeout

met*_*man 1 javascript

我有一个对象,我想在其中编写一个自执行函数.我有这样的事情:

var testObject= (function () {
function testObject() {
    this.counter = 0;
}

testObject.prototype.Cycle = function () {
    try {
        console.log("tick, ID: " + this.counter++);

        setTimeout(this.Cycle, 2000);
    } catch (ex) {
        console.log(ex);
    }
};

return testObject;
})();
Run Code Online (Sandbox Code Playgroud)

它只工作一次.因为它在第一次运行时给出,tick, ID: 0并且在第二次运行时给出tick, ID: undefined.实现自执行功能的最佳方法是什么?

Den*_*ret 8

你遇到的问题是this,在回调中,是window.

一个办法 :

testObject.prototype.Cycle = function () {
    try {
        console.log("tick, ID: " + this.counter++);
        setTimeout(this.Cycle.bind(this), 2000);
    } catch (ex) {
        console.log(ex);
    }
};
Run Code Online (Sandbox Code Playgroud)

但是你不需要所有这些代码.你可以这样做:

(function cycle(i){
    console.log("tick, ID: " + i);
    setTimeout(cycle, 2000, i+1);
})(0);
Run Code Online (Sandbox Code Playgroud)