pavanarya

Let us share the knowledge

Inheritance In Javascript Using Prototype Keyword

with 2 comments

Hi,
In my previous post we saw how to create classes and methods in java script.

Now in this post we will see how to create super classes and sub classes in java script using prototype keyword.

When to use Prototype Keyword

Now let us create a simple class(Person) with a single parameter “Name”.

<script type="text/javascript">
<script type="text/javascript">
function Person(name)
{
this.Name=name;
} 

var person1=new Person('pavan');
alert(person1.Name);

var person2=new Person('Kiran');
alert(person2.Name);
</script>

So in the above code we are having a class Person with a constructor that accepts a parameter ‘name’. And we are creating 2 objects person1 and person2 and accessing the property Name in alert.

Now let us add a custom property to an object of java script

<script type="text/javascript">
function Person(value)
{
this.Name=value;
} 

var person1=new Person('pavan');
person1.age=2;

alert(person1.age);
alert(person1.Name);
</script>

In the above code we are adding a custom property age to the object person1 and we are trying to use that custom property in alert.

<script type="text/javascript">
function Person(value)
{
this.Name=value;
} 

var person1=new Person('kiran');
person1.age=2;

alert(person1.age);
alert(person1.Name);

var person2=new Person('pavan');

alert(person2.age);
alert(person2.Name);
</script>

In the above code in addition to adding custom property age to object person1 we created another object person2 but for this object person2 we are not adding the custom property age. But we are trying to use that in alert as follows alert(person2.age) and this will alert undefined.

So from this what we understood is if we add a custom property to an object then it reflects only to that particular object and even though we create a new object to the same class that custom property will not reflect. This is sometimes required but sometimes we need these custom properties to reflect on all the objects created.

In our example “age” is the custom property, each and every person object should have that property. Now this is the time to introduce our hero that is prototype keyword.
In order to make use of prototype keyword, it should be appended to the object just before adding the custom property to it.

<html>
<head>
<script type="text/javascript">
function Person(value)
{
this.Name=value;
} 

Person.prototype.age="23" //we are creating a custom property age to Person class. Now this will reflect on all the instances of Person class

var person1=new Person('pavan');
alert(person1.Name);
alert(person1.age);

var person2=new Person('Kiran');
alert(person2.Name);
alert(person2.age);
</script>
</head>
</html>

Now let us create a custom method and add that to Person class using prototype so that it reflects on all instances of Person class.



<script type="text/javascript">
function Person(value)
{
this.Name=value;
} 

Person.prototype.age="23"
Person.prototype.customMethod=function(){ alert("I am custom prototype method");}
// we are adding a custom method using prototype to Person class
var person1=new Person('pavan');
alert(person1.Name);
alert(person1.age);
person1.customMethod();//making use of custom method

var person2=new Person('Kiran');
alert(person2.Name);
alert(person2.age);
person2.customMethod();//making use of custom method
</script>

How prototype object works:
Generally when ever we are accessing a property of a class the interpreter search the properties of that class and if it doesn’t find then it will look at the prototype object created for that class.

SubClass and SuperClass in Javascript

Upto now we saw how to add custom properties, methods and add them to a particular class. Let us jump into parent child class relationships.

Let us create a child class to our Person class and name it as Employee class.



<script type="text/javascript">
function Person(name)
{
this.Name=name;
this.firstname="arya";
} 

function Employee(id,title)
{
this.id=id;
this.title=title;
}

var person1=new Person('pavan');
var employee1=new Employee('kt848','trainee');
alert(employee1.id);
alert(employee1.firstname);// return undefined 
</script>


so in the above code we are having two classes Person and Employee. Here let us assume that Employee class is the child class for Person class.
So i am trying to access a property of Person class with employee class object alert(employee1.firstname) but this will return undefined because we didn’t manually mentioned that Employee class is child class of Person class.
Now let us do that

<script type="text/javascript">
function Person(name)
{
this.Name=name;
this.firstname="arya";
} 

function Employee(id,title)
{
this.id=id;
this.title=title;
}

Employee.prototype = new Person();

var person1=new Person('pavan');
var employee1=new Employee('kt848','trainee');
alert(employee1.id);
alert(employee1.firstname);//this will return arya
</script>

So here after creating the two class we are setting up the parent child class relation between them as follow.

Employee.pototype=new Person();

So this is going to set the prototype hierarchy that is whenever we are trying to access a method or variable using Employee’s instance and if it is not found with Employee class then it will immediately go and search in Person class. If it doesn’t find that variable or method even there then it is going to return undefined.

alert(employee1.firstname);
So in our case initially it will search for firstname in employee class and then it will search in Person class.

Now let us watch this particular code execution in firebug.

So if we see the image in the watch section at the top the employee object that is employee1 is pointing to Person Class constructor. This is because when we assigned Person class to Employee’s prototype we explicitly changes the constructor to Person class so inorder to change that we should add the following line

Employee.prototype.constructor = Employee;

<html>
<head>
<script type="text/javascript">
function Person(name)
{
this.Name=name;
this.firstname="arya";
} 

function Employee(id,title)
{
this.id=id;
this.title=title;
}

Employee.prototype = new Person();
alert(Employee.prototype.constructor);//----------------->1
Employee.prototype.constructor = Employee;
alert(Employee.prototype.constructor);//------------------>2
//Employee.superclass = Person.prototype;
var person1=new Person('pavan');
var employee1=new Employee('kt848','trainee');
</script>

we can see the change made that statement with the alert box 1 and 2 in above code.

Now let us try to initialize try to change our code a little bit. Now we will create a Person class that will initialize name property and Employee class will initilize 3 properties id,title,name. Note here we are going to call the Person class constructor to initialize name property of Employee . Now comes in the actual flavor of inheritance.

<script type="text/javascript">
function Person(name)
{
this.initialize(name);
} 

Person.prototype.initialize=function(name){
this.name=name;
}

function Employee(id,title,name)
{
this.id=id;
this.title=title;
this.initialize(name);
}

Employee.prototype = new Person();
Employee.prototype.constructor = Employee;

var employee1=new Employee('kt848','trainee','pavan');
alert(employee1.name);
alert(employee1.id);

</script>

let me explain about this function in detail.
Previously we used to initialize the properties of Person class in the Person Class itself. But now we added a custom method initialize() to initialize property of Person class and added that to Person using Prototype. So this initialize() can be used by all instances of Person class.

Now in Employee class out of 3 parameters we are initializing 2 parameters there itself but coming to third parameter we are calling the method initialize() but we dont have definition of that in Employee class and in these lines

Employee.prototype = new Person();
Employee.prototype.constructor = Employee;

We are specifying Employee is a prototype of Person . So the interpreter will search for initialize() in person class as it is not found in Employee class.So it will use the initialize() prototype of Person class to initialize name.

Now let us take another case:

Suppose there are 3 classes A,B,C. A is super class of B, B is Super Class of C.

Now A contains a prototype method just like the initialize() method in the above code piece.
Also B contains a method initialize() with same name which is added by using prototype to B.
So A is having its own method and B is also having its own method with same names.
Now are establishing the parent child relationship using above mentioned processes.

Now c is accessing initialize() and it doesnt have that method so the interpreter will access the same method present in B because we established Prototype relation ship between them. Now B wants to use the initialize() method present in A. But at the time of execution the interpreter will check for that method in B and we are having that method initialize() B so it will execute the method present in B itself and it will not go for the initialize() method present in A even though there is a prototype relationship between A and B.

So in this case we are supposed to use ‘call’ method which is default method for all object

B.superclass.initialize.call(this, parameter1, parameter2,...paametern);

What this statement describes is B wants to use the initialize() of superclass(here A is super class of B) even though B is having its own initialize() method.

My Final code for Employee -Person Class

<html>
<head>
<script type="text/javascript">
function Person(name)
{
this.initialize(name);
} 

Person.prototype.initialize=function(name){
this.name=name;
}

function Employee(id,title,name)
{
this.id=id;
this.title=title;
this.initialize(name);
}


Employee.prototype = new Person();
Employee.prototype.constructor = Employee;
Employee.superclass = Person.prototype;


var employee1=new Employee('kt848','trainee','pavan');
alert(employee1.name);
alert(employee1.id);

</script>
</head>
</html>
About these ads

Written by pavanarya

January 1, 2012 at 3:34 pm

Posted in Java script

2 Responses

Subscribe to comments with RSS.

  1. Nice Article, it is very useful

    We can submit .net related article links on http://www.dotnettechy.com/ to increase traffics

    Micle

    January 3, 2012 at 2:26 pm

  2. Hi pavan,
    Just to add a note here.
    I am working on, some javascript arrays and i found some thing weired while using the protoType key word for system defined array object.
    I am using yui.. And had one js file which is common to all of my pages

    Introducing this piece of code, in that js file had exploded almost all the pages..

    Code Piece Which i Added:
    //Checks Whether the specifie element is present in the array or not.
    Array.prototype.contains = function(element) {
    for (var i = 0; i < this.length; i++) {
    if (this[i] == element) {
    return true;
    }
    }
    return false;
    }

    The reason for this:
    Adding the property to the standerd objects is not a wise thing to do..
    One can check that with this piece of code stated below,

    Type this, in the address bar of your browser
    javascript:Array.prototype.foo=1; var a = [1,2,3,4,5];for (x in a){alert(x);}

    or this one,
    javascript:Array.prototype.contains = function(element) {for (var i = 0; i < this.length; i++) {if (this[i] == element) {return true;}} return false;}; var a = [1,2,3,4,5];for (x in a){alert(x);}

    You will see, foo/contains comes up as an alert.

    So, the JavaScript library(YUI or jQuery,etc…) may be using these for– in loops, internally that we are not aware..
    All those will be breaked by using this.

    Bottom line: Bettter not to use this Proto Type for standard objects.

    Sri Harsha Varada

    February 1, 2012 at 10:52 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 68 other followers

%d bloggers like this: