Javascript inheritance and method overriding

The Coding Monk picture The Coding Monk · Jan 24, 2011 · Viewed 22.8k times · Source

Assume I have a class like this:

function Widget() {
    this.id = new Date().getTime();
    // other fields
}
Widget.prototype = {
    load: function(args) {
        // do something
    }
}

From this class I created some other classes which inherit the same prototype but have some added methods. What I want to do is being able to define a load() method in the sub-classes which first calls the parent method and then execute some code. Something like:

SpecialWidget.prototype = {
    load: function(args) {
        super.load(args);
        // specific code here
    }
}

I know there's no super keyword in Javascript but there must be a way to do this.

Answer

karim79 picture karim79 · Jan 24, 2011

You can simulate it like this:

SpecialWidget.prototype = {
    load: function(args) {
        Widget.prototype.load.call(this, args);
        // specific code here
    }
}

Or you can create your own super property like this:

SpecialWidget.prototype.parent = Widget.prototype;

SpecialWidget.prototype = {
    load: function(args) {
        this.parent.load.call(this,args);
        // specific code here
    }
}