I am seeing problem with passing object method as argument to setTimeout.
I know inside nested function, scope of this need to be set manually but what if i directly pass function object, in my case this.counting. What is the need of declaring anonymous function as first argument, this.counting is already a function.
Mozilla also uses function(msg) {self.remind(msg);} instead of this.remind inside setTimeout first argument.
function Timer(count,start){
this.count = count;
this.start = start;
}
//below code works
Timer.prototype.counting = function(){
var self = this;
setTimeout(function(){self.counting();},this.start);
console.log(this.count);
this.count++;
};
//below code doesn't work
/*
Timer.prototype.counting = function(){
setTimeout(this.counting,this.start);
console.log(this.count);
this.count++;
};
*/
var t1 = new Timer(0,1000);
t1.counting();
var t2 = new Timer(100,1000);
t2.counting();
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…