This article will help to get a better understanding of implementing inheritance in javascript using the prototype feature in javascript. I was thinking about inheritance(Refer OOPS, google it you will get lots). Then my next thought was how to implement it in JAVASCRIPT :) .
One can find inheritance in most of the language, dotnet, C#, PHP where OOPS concept is there.
Now, lets concentrate on our current topic.

Here we go,

First let me declare parent class,

var Parent = function(){};

Above looks like a normal function declaration, but javascript is so flexible as one should know.
so if you want to declare an object for the above class, just do

var objectParent = new Parent();

Now let me add ‘alert1′ method to our Class ‘Parent’,

Parent.prototype = {
alert1: function(){alert("Parent1");}
}

for more information on keyword ‘prototype’ please google :) .

Its time to declare a Child class now,

var Child = function(){};

And adding the inheritance to ‘Child’ from Parent,

Child.prototype = new Parent();

Now adding method which is specific to class ‘Child’

Childprototype.alert2 = function(){
alert("Child1")
};

Now lets create an instance of ‘Child’ class

objectChild = new Child();

And to access the methods its like,

objectChild.alert1();
objectChild.alert2();

Thats all folks, so simple :) .

Just copy the below code and we should be able to test inheritance,

var Parent = function(){};
Parent.prototype = {
alert1: function(){alert("Parent1");}
}

var Child = function(){};
Child.prototype = new Parent();

Child.prototype.alert2 = function(){ alert("Child1")
};
objectChild = new Child();

objectChild.alert1();
objectChild.alert2();
Be Sociable, Share!