To pass arguments from a constructor to its base, you can execute the base constructor with .call()
or .apply()
:
var Pet = function (age, name) {
Animal.call(this, age);
// ...
};
Both will allow the base constructor to be called with the same context (this
) value.
You'll also only want to modify the prototype
outside of any constructor since its properties and their values will be shared among all instances.
var a = new Animal(10);
var b = new Animal(15);
console.log(a.age); // 15 rather than its own 10
To set additional properties per-instance, you'll want to instead modify the context this
:
var Animal = function (age) {
this.age = age;
};
var Pet = function (age, name) {
Animal.call(this, age);
this.name = name;
};
And, regarding constructor
properties:
The initial prototype
object will already have the constructor
property set. So, is isn't usually necessary to set it yourself:
Animal.prototype.constructor = Animal;
Unless you're replacing the initial prototype
object completely. For such cases, you'll want to reset the constructor
afterwards or it'll be set to initial object that's being replaced.
Pet.prototype = Object.create(Animal.prototype);
Pet.prototype.constructor = Pet;