Friday, November 15, 2013

JavaScript : Prototype Property and Inheritance

You may also like to see:
In JavaScript each object has a property of Prototype, allow to add a property or function to an object.

In JavaScript there is no concept of class, you need to create an object, then you can extend it actually that object is in JavaScript is a class. Prototype allows to add new functionality to existing object like adding subString(),reverse() to a string object.

If we take this like we have a Employee class, there are different types of Employees like Managers, Supervisors, Agents etc. But each type is actually inheriting Employee.

Example (JsFiddle Demo):

//Define a functional object to hold employee in JavaScript
var Employee = function(name) {
    this.name = name;
};

//Add dynamically to the already defined object a new getter
Employee.prototype.getName = function() {
    return this.name;
};

//Create a new object of type Employee
var judy= new Employee("Judy");

//Try the getter
alert(judy.getName());

//If now I modify employee, also Judy gets the updates
Employee.prototype.alertMyName = function() {
    alert('Hello, my name is ' + this.getName());
};

//Call the new method on john
judy.alertMyName();

Here in above code we extended the base object, now we will create a child object and inherit it from base class (JsFiddle Demo).

//Create a new object of type Manager by defining its constructor. 
// It's not related to Employee for now.
var Manager = function(name) {
    this.name = name;
};

//Now I link the objects and to do so, we link the prototype of Manager 
//to a new instance of Employee. The prototype is the base that will be
//used to construct all new instances and also, will modify dynamically
//all already constructed objects because in JavaScript objects retain 
//a pointer to the prototype

Manager.prototype = new Employee();     

//Now I can call the methods of Employee on the Manager, let's try,
//first I need to create a Manager.
var myManager = new Manager('John Smith');
myManager.alertMyName();

//If I add new methods to Employee, they will be added to Manager,
//but if I add new methods to Manager they won't be added 
//to Employee. Example:
Employee.prototype.setSalary = function(salary) {
    this.Salary = salary;
};
Employee.prototype.getSalary = function() {
    return this.Salary;
};

//Let's try:       
myManager.setSalary(30000);
alert(myManager.getSalary());

judy.setSalary(60000);
alert(judy.getSalary());

//Now if I added a property to Manager 
Manager.prototype.Projects =function(){
    return "Handling multiple projects";
}

//Projects function will be available for managers instances
alert(myManager.Projects());

//it wont be available for employee judy
if((typeof judy.Projects) !== "function")
    alert('function not available');

While as said I cannot call Projects() on a Employee. Because parent class does not have implementation of child class function.

//The following statement generates an error.
judy.Projects();

How Prototype chain works?

When it calls the parent class function, it firstly find member in the current object of Manager, but as alertMyName() was not available there so it searches in prototype, and it keep finding until it find the function or find the prototype null.

Prototype chain can be extended as many level as required, each time by setting the prototype of the child class equal to an object of the parent class. If you do not use prototype then it becomes a static and only available for current object. As we know object in JavaScript is a class and making a static function only available for that particular object and for other object of same type cannot access the same function while creating function with prototype is available in all objects.

Here is a short example (JsFiddle Demo).

var myClass =function(){};
myClass.myFunction = function() { 
  alert('Hello Static Function');
} 
//current object will call it function as it associated to it
//it can be called with this object only
myClass.myFunction();
//now create instance variable
var objectOne = new myClass();
var objectTwo = new myClass();

//now calling myFunction with multiple instances will throw error
objectOne.myFunction();
objectTwo.myFunction(); 


on the other hand with Prototype (JsFiddle Demo):

var myClass =function(){};
myClass.prototype.myFunction = function() { 
  alert('Hello class Function');
} 

//now create instance variable
var objectOne = new myClass();
var objectTwo = new myClass();

//now calling myFunction with multiple instances will throw error
objectOne.myFunction();
objectTwo.myFunction(); 


You may also like to see:


If you want to add something on this post please comments.

2 comments:

  1. we can also add property to object directly like this
    var obj={};
    obj.name ="myObject"
    so what is the difference using prototype property?

    ReplyDelete
    Replies
    1. plz read the section "How Prototype chain works?"

      " If you do not use prototype then it becomes a static and only available for current object. As we know object in JavaScript is a class and making a static function only available for that particular object and for other object of same type cannot access the same function while creating function with prototype is available in all objects."

      example is given above.

      Delete