To implement inheritance in Javascript, one generally does the following 2 steps;
Say I have a base class "Animal"
var Animal = function(name){
this.name = name;
}
I now want to derive a sub class "Dog" from the same. So I would say
var Dog = function(name) {
Animal.call(this,name);
}
So I am calling my parent class constructor from my derived class constructor. The 2nd step is to set the prototype as follows;
Dog.prototype = new Animal();
Now I can access any of the base "Animal" class properties from within my derived class Dog.
So my question is why are these 2 steps necessary ? If we just call the base class constructor using
Animal.call(this,name);
isn't that enough for implementing Inheritance ?
Why do we also need to set the prototype property using Dog.prototype = new Animal(); ?
I wanted to understand what each of the above 2 steps does ?
Animalcan also inherit using a prototype chain. Simply calling the parent constructor will not keep that inheritance chain.call()doesn't perform inheritance, it simply adds new members (properties or methods) tothis, whilenewinherits any members of the parent class prototype. See my answer for details :)