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!
prototypewithin a constructor. Theprototypeis shared among all instances while the constructor should then modify the individual instance (this).Pet.prototype.constructor = Pet;line does nothing when it’s before the part where you set the prototype. Also,Pet = function(age, name)is undeclared and you should usefunction Pet(age, name)(which also gives it a name and works in strict mode).