Possible Duplicate:
Why are my JS object properties being overwritten by other instances
Why isn’t the attribute “t” changed after setT was called? I would expect “4” as output, but it prints “default”.
function Car(i) {
var id = i;
var t = "default";
this.getT = function() { return t; }
this.setT = function(p) {
t = p; // attribute t isn't changed ..
}
}
function ECar(id) {
Car.call(this, id); // super constructor call
this.setT = function(p) { // override
ECar.prototype.setT.call(this, p); // super call
}
}
ECar.prototype = new Car();
ecar = new ECar(3);
ecar.setT(4);
alert(ecar.getT()); // prints default, not 4
At this line
ECar‘s prototype get a context, in which allECar‘s instance will be shared.This line will call at that context, not what has been created while calling super at
Car.call(this, id);.You can fix your code with
but it would be better (and more readable) to use real prototypes, such as
Edit: note (as @Bergi suggested)
You should only use
Child.prototype = new Parent()as inheritance if you must support legacy browsers & then you should only use empty constructors.The most (other-language) compatible way in JavaScript for inheritance is
(MDN says it is supprted from IE 9)