Friday, 6 March 2009

Inheritance in JavaScript

A few days ago I had to implement multi-searcher functionality in javascript.
It was something like a box with three searchers. You may pick searcher (i.e. Google, Wikipedia or Yahoo), enter the phrase, click Search button and results were shown below.

This task was perfect to use a base class for all searchers an then each type
of searcher as derived class. Yes, indeed, but how would you do do it in javascript?

I don't wanna talk how much time I spent on it, but finally I have found very simple and pretty obvious solution.

First of all we create a base function/class

     function BaseClass() {}
     BaseClass.prototype =
         type: "BaseClass",

         GetType: function() { return this.type; },

         WriteType: function() { document.writeln(this.GetType()); }

This is rather the dummy class, but reffer to my aim.
So we have type field there, and two simple methods.

Now I can just write derived classes

     FirstDerivedClass.prototype = new BaseClass;
     FirstDerivedClass.constructor = FirstDerivedClass;
     function FirstDerivedClass()
         this.type = "FirstDerivedClass";

     SecondDerivedClass.prototype = new BaseClass;
     SecondDerivedClass.constructor = SecondDerivedClass;
     function SecondDerivedClass()
         this.type = "SecondDerivedClass";

And thats it!
We have a derived class/functions in javascript.

     FirstDerivedClass.prototype = new BaseClass;

that line assign prototype to FirstDerivedClass.

     FirstDerivedClass.constructor = FirstDerivedClass;

that line assigns separate contructor to FirstDerivedClass.
And in that way;

we can call base class constructor, please note that it is called earlier too (here - FirstDerivedClass.prototype = new BaseClass;), but by using call method we can pass additional arguments to base class if we want to.

In that simple way we obtain the inherit-like result.
Code executed below

     new BaseClass().WriteType();
     new FirstDerivedClass().WriteType();
     new SecondDerivedClass().WriteType();

shows following text on the page

     "BaseClass FirstDerivedClass SecondDerivedClass"

and that is exactly what I needed and expected.