Prototyping inheritance, setTimeout and clearTimeout
I am embarrassed.
I am creating 2 objects that use the same prototype, but when the second one runs the method run()
, I expect it to stop the timeout that is set for the shared inherited object timer
( Foo.prototype.timer
).
If I change everything to use a global variable instead Foo.prototype.timer
, it works.
Why doesn't this clear if both objects are 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();
(copy and run this code in the console to see this issue.)
source to share
With that.timer
you don't assign a prototype - it that
is an instance and therefore a new property will be created there. To set a property to protoype, you will need to do this explicitly:
Foo.prototype.timer = setTimeout( calc, 200 ); // or, more verbose:
Object.getPrototypeOf(that).timer = setTimeout( calc, 200 );
source to share
how NOT to make it unique? I thought unique things were only located on Foo () itself
Anything you declare with this
will be unique to the instance, even if it is declared inside a prototype. What gets shared is the prototype, not the properties of each object.
Try with a module instead of a global variable, this way you can still make the variable private but shared:
var Foo = (function FooClass() {
var timer;
function Foo() {
...
}
Foo.prototype = {
...
};
return Foo;
}());
source to share