Javascript Inheritance

March 22, 2010

In this post I will cover the following topics:

  • Understanding how the prototype works
  • Using the prototype for inheritance
  • The Inherit Function
  • Overriding methods

In one of my previous post i talked about Object Oriented Javascript , where i mostly talked about class encapsulation. In this post i would like to advance to another important issue of object oriented – inheritance.

In Javascript inheritance is not that straightforward as it is in most object oriented languages, where a simple keyword will allow you to inherit from a class. In Javascript you need a several steps in order to achieve inheritance. Moreover, Javascript’s inheritance is prototypal. The language flexibility allows you to use standard class based inheritance, or a more complex prototypal inheritance (which I will not get into in this post).

Standard Inheritance

First lets declare a simple function to be used as a base class:


/*Class Animal*/
function Animal(name){
    this.name = name;
}

Animal.prototype.getName = function(){
    return this.name;
}

Now to create an instance of the Animal class we invoke the constructor with the new keyword:


var monkey = new Animal("monkey");
alert(monkey.getName());

Now we will create a class that inherits from the Animal class:


/*Class Monkey*/
function Monkey(name,specie){
    //call the superclass constractor in the scope of this
    Animal.call(this,name);
    this.specie = specie ;
}

Monkey.prototype = new Animal(); //prototypal chain
Monkey.prototype.constructor = Monkey; //set the constructor to Monkey
Monkey.prototype.getSpecie(){
    return this.specie;
}

Now let’s go over about what just happened here:
First we created a constructor function as we did with the Animal class, but this time we called the superclass constructor using the call method and passed the name argument. When we create a new instance of Monkey the Javascript engine creates for us an empty object and runs the constructor with this empty object, where this refers to this empty object. in order to do the same for the superclass we do it manually with the Animal.call(this,name); that will invoke the Animal constructor with the empty object.
After that we set up the prototype chain. Let’s explain what that means first. In Javascript, the prototype attribute points to either another object or null. When a member of an object is accessed, Javascript looks for this member in the prototype object if it doesn’t exist in the current object. It will continue to go up the chain of prototype until it will find or the prototype will be null.

To set up the prototype chain we set the prototype to a new instance of the superclass: Monkey.prototype = new Animal();
When we set the prototype attribute to an instance of Animal, the constructor attribute is deleted; this is why we need to set the constructor attribute back to Animal.
To create an instance is the same as it used to be:


var monkey = new Monkey("monkey","orangutan");
alert(monkey.getName());
alert(monkey.getSpecie());

Inherit Function

We could wrap all this inheritance code into a function to help us. I came across this implementation on the web, and I added to my own library, but I can’t remember where I took it from. Anyway it’s a cool code to use, and I’ll explain how it works:


function Inherit(sub,super){
    var thinF = function(){};
    thinF.prototype = super.prototype;
    sub.prototype = new thinF();
    sub.prototype.constructor = sub;
    sub.super = super.prototype;
    if( super.prototype.constructor == Object.prototype.constructor ){
    super.prototype.constructor = super;
    }
}

Now we can do the following:


/*Class Monkey*/
function Monkey(name,specie){
    //call the superclass constractor in the scope of this
    Monkey.super.constructor.call(this,name);
    this.specie = specie ;
}

Inherit(Monkey,Animal);

I will explain now about the Inherit function since it covers some important issues.
The function does the same things that we did manually, except the following:

  • Adds the empty class thinF – This is done to increase performance. Since we need to create a new instance of the super to be set to the prototype for the sub class, we (usually) don’t want to instantiate a new instance, since we only need the prototype of this class, so we save some memory and CPU this way.
  • Saves the super prototype – this way we can call the constructor without knowing the name of the super.

Overriding Methods

Overriding is pretty simple, you just need to declare the method name again in the sub class. If we use the Inherit function we can also call the super implementation since we have the prototype of the super:


Monkey.prototype.getName = function(){
    var name = this.specie + " is a " + Monkey.super.getName.call(this);
    return name;
}
Bookmark and Share
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • E-mail this story to a friend!
  • FriendFeed
  • LinkedIn
  • StumbleUpon
  • Twitter

tags: , ,
posted in Blog by Amir Harel

6 Comments to "Javascript Inheritance"

  1. gilbeRt_fox wrote:

    Sweet! =) Thanks for this clear post

  2. Yossef Bitton wrote:

    Good one, as Gilbert wrote, clear.

    Might be a good supplemental to mention that trying to add abilities this way to the “Math” object, is not by using the same approach as any other object, for it had no constructor and it gives no access to its “prototype” method.

  3. Implementing Multiple Inheritance in Javascript | Amir Harel wrote:

    [...] Javascript Inheritance [...]

  4. LLOYD wrote:


    Medicamentspot.com. Canadian Health&Care.Special Internet Prices.Best quality drugs.No prescription online pharmacy. Online Pharmacy. Order drugs online

    Buy:Nexium.Lumigan.Actos.Human Growth Hormone.Synthroid.Zovirax.Mega Hoodia.Zyban.Arimidex.Retin-A.Prednisolone.Accutane.Petcam (Metacam) Oral Suspension.Valtrex.Prevacid.100% Pure Okinawan Coral Calcium….

  5. carlos wrote:

    Awesome!

  6. carlos wrote:

    Awesome!

 
Powered by Wordpress and MySQL. Theme by openark.org