JavaScript : Inheritance in JavaScript

JavaScript is not a class based language, So it is bit confusing for most of developers familiar with languages like Java or C#.In-order to understand how inheritance work in JavaScript you need to have a good understand about how prototype objects work in JavaScript.

Every object in JavaScript has an internal link to a object. That object is called prototype object. When we trying to access a property from a object JavaScript will first look in that object and if that property is not found next the prototype object will be searched . Refer this link for more details.

So if we want want to inherit properties from another object we can simply point prototype to that object.

Lets try an example

There are two constructor functions

function Animal(){
    this.name="Animal";    
    this.sleep=function(){
        return this.name+" sleeps";
    }
}

function Dog(){
    this.name="Dog";
}

function Bird(){
    this.name="Bird";
}

Now I want to inherit properties from Animal object in Dog and Bird objects. So I point prototypes of Dog and Bird objects to a Animal object

Dog.prototype= new Animal();
Bird.prototype= new Animal();

After that contructors of prototypes of Bird And Dog objects have to be set to relevant functions because they are changed in the previous step.(Read more about this step from this link)

Dog.prototype.constructor=Dog;
Bird.prototype.constructor=Bird;

Now we can use properties from Animal object in Dog and bird classes. Here I have used sleep() function of Animal object in Dog and Bird Object.

var dog1= new Dog();
var bird1 = new Bird();

document.write(dog1.sleep()+"<br/>");
document.write(bird1.sleep()+"<br/>");

Here is the complete code for Inheritance in JavaScript.

function Animal(){
    this.name="Animal";    
    this.sleep=function(){
        return this.name+" sleeps";
    }
}

function Dog(){
    this.name="Dog";
}

function Bird(){
    this.name="Bird";
}

Dog.prototype= new Animal();
Bird.prototype= new Animal();

Dog.prototype.constructor=Dog;
Bird.prototype.constructor=Bird;

var dog1= new Dog();
var bird1 = new Bird();

document.write(dog1.sleep()+"<br/>");
document.write(bird1.sleep()+"<br/>");

Please add a comment if you are not clear with something or you have something to add.
Here is another document from MDN that describes inheritance with Object.create() method.

No comments:

Post a Comment