Reputation: 672
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
. What is the best way to achieve self executing function?
Upvotes: 2
Views: 4010
Reputation: 382122
The problem you have is that this
, in the callback, is 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);
Upvotes: 12