Monday, May 17, 2010

Inheritance in JavaScript

You may know it before that we can implement OOPs concepts in Javascript. I am going to demonstrate here one of them "Inheritance in Javascript".
Before going head let me tell  you some facts about javascript

  1. In javascript every function can be used to create an object out of it with "new" operator. 
  2. Javascript objects are hashed and interpreted that means you can add any property to them on runtime. 
  3. Every function (when used as class) is inherited by an inbuilt function(class) called "prototype" of that function. the constructor of your function/class is implemented inside the prototype of your function/class. So whatever properties or methods you add in prototype would be available to all objects of your function/class by default.
  4. When any property/method is accessed from an object, interpreter first tries to find it inside the object itself, if it is not there then it looks into prototype class of that object and keeps on going up in its prototype chain unless it finds it. the super base of any object is prototype of "object" class itself. If it does not find it after crawling upto "object" prototype then it throws error of "undefined" or "not found".
Now let me give you an example how to implement inheritance

function Person()
    this.eyes = 2;
    this.legs = 2;
    this.color = "white";

Now I want to derive another class Man out of it
to do so you need to write as following

Man.prototype.constructor = Man; //this line will tell that man object will be instantiated from its own prototype
Man.prototype = new Person;  //this line will  hook Person into Man's prototype chain

Please note that you have to write the above two lines before creating Man class

now I am writing a "Man" class

function Man()
    this.color = "black";

just to explain you how you can add some properties/methods in objects prototype directly, you can refer following example

Person.prototype.legs = 4;
Man.prototype.legs = 2; = "black";

Ok, now I am going to create an object of Man class

var m = new Man(); //m is an  object of Man

alert(m.color); // the interpreter will look into class Man first and will popup black
alert(Man.prototype.color); // since prototype of Man does not contain color property, it will move up the prototype chain and will look into Person prototype and popup "white"
alert(m.legs); //legs are not defined in object "m", it will look ito prototype of "m" and will pop up 2

I hope you must have understood by now how this whole inheritance is going to work. This is not different than how you find it working in C#/VB.Net or any other language.

No comments:

Post a Comment