Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Inheritance ; call and prototype

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 ?

like image 969
copenndthagen Avatar asked Apr 20 '26 12:04

copenndthagen


1 Answers

var Animal = function(name){
    this.name = name;
}
Animal.prototype.sleep = function() {
    console.log("Sleeping")
}

... 
// Without this line:
Dog.prototype = new Animal();

// the following code will fail, since `d` does not contain `sleep`
d = new Dog();
d.sleep();

Animal.call(this,name); simply calls the function Animal, but using the same this as the calling function.

Dog.prototype = new Animal(); sets the prototype of the prototype. However, Dog.prototype = Object.create(Animal.prototype) might be more correct.

like image 87
Eric Avatar answered Apr 23 '26 02:04

Eric