I’m confused.
I’m creating 2 objects that share the same prototype, but when the second one fires the run() method, I would expect it to stop the timeout which is set on the shared inherited object timer (Foo.prototype.timer).
If I change everything to use a global variable instead of Foo.prototype.timer, this works..
Why is it not clearing if both objects share the same Foo.prototype.timer?
function Foo(){
// generate a random ID to show which object we're on
this.id = Math.floor(Math.random() * 1000) + 2;
}
Foo.prototype = {
run : function(){
var that = this,
count = 0;
this.stop();
function calc(){
console.log(that.id);
if( count++ < 20 )
that.timer = setTimeout( calc, 100 );
}
that.timer = setTimeout( calc, 200 );
},
stop : function(){
clearTimeout(this.timer);
}
}
// initiating
var foo = new Foo();
foo.run();
var bar = new Foo();
bar.run();
(please copy and run this code in your console to see this issue.)
With
that.timer, you do not assign to the prototype –thatis the instance, and so a new property will be created there. To set the property on the protoype, you will need to do it explicitly: