Tag Archives: OOP

Object Oriented JavaScript Inheritance

Here”s the short explanation of how to do inheritance with javascript. This was the best site I found on the subject and I tell the same story albeit tersely.

I defined a base class, called Base just to be clear:

Base = function()
{
}

Base.prototype.say = function(foo)
{    
    return foo;
}

Then I defined a class to extend Base called Extender:

Extender.prototype = new Base;

function Extender()
{
    // this line calls parent class constructor
    // like saying super() in Java
    // or like using parent::Base() in PHP
    Base.call(this);
}

You will have problems if you try to say Extender = function() {}…at least it didn”t work for me written that way.

Override say() method of parent class, but I also call the parent class method:

Extender.prototype.say = function(foo)
{
    // in this case we override but also call the parent method
    return 'extend ' + Base.prototype.say(foo);
}

This was tested with jsunit.