set attribute with javascript super method

javascript, super

Solution

`ECar.prototype = new Car();`

At this line `ECar`'s prototype get a context, in which all `ECar`'s instance will be shared.

`ECar.prototype.setT.call(this, p);`

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

function ECar(id) {  
  Car.call(this, id);  // super constructor call
  var carSetT = this.setT;
  this.setT = function(p) {
    carSetT.call(this, p);
  }
}

but it would be better (and more readable) to use real prototypes, such as

function Car() {}

Car.prototype.getT = function () { /* ... */ };
Car.prototype.setT = function () { /* ... */ };

function ECar() {}

ECar.prototype = new Car();
ECar.prototype.setT = function () { /* ... */ };

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

Child.prototype = Object.create(Parent.prototype)

(MDN says it is supprted from IE 9)

Problem

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 ```

Original source

Related problems