Reputation: 49
I have this code.
Animal = function(age)
{
Animal.prototype.age = age;
};
Animal.prototype.constructor = Animal;
Animal.prototype.Walk = function()
{
console.log("Animal Walking");
};
Pet = function(age, name)
{
Pet.prototype.name = name;
};
Pet.prototype.constructor = Pet;
Pet.prototype = Object.create(new Animal());
Pet.prototype.DoTricks = function()
{
console.log(this.name + " is doing tricks!");
};
var pet = new Pet(5, "Barney");
console.log(pet);
All Animals have an age and can walk. Pet Inherits Animal through its prototype. Pets have names and can do tricks, they also have an age and can walk.
How can I organise my code to achieve this behaviour? At the moment I can make it so Pets can walk but their age is left undefined since I cannot pass its age through the constructor.
Many Thanks!
Upvotes: 1
Views: 57
Reputation: 123473
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;
Upvotes: 1