[英]setTimeout with self executing function
I have an object and I want to write a self executing function within it. 我有一个对象,我想在其中编写一个自执行函数。 I have something like this: 我有这样的事情:
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;
})();
And it works only once. 而且它只能工作一次。 Because at the first run it gives tick, ID: 0
and at the second time it gives tick, ID: undefined
. 因为在第一次运行时,它将给出tick, ID: 0
而在第二次运行时,它将给出tick, ID: undefined
。 What is the best way to achieve self executing function? 实现自我执行功能的最佳方法是什么?
The problem you have is that this
, in the callback, is window
. 你的问题是, this
,在回调,是window
。
A solution : 一个解法 :
testObject.prototype.Cycle = function () {
try {
console.log("tick, ID: " + this.counter++);
setTimeout(this.Cycle.bind(this), 2000);
} catch (ex) {
console.log(ex);
}
};
But you don't need all this code. 但是您不需要所有这些代码。 You may simply do : 您可以简单地做:
(function cycle(i){
console.log("tick, ID: " + i);
setTimeout(cycle, 2000, i+1);
})(0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.