A Stab At Javascript Inheritance

By james

Here is the working code for implementing an inheritance model in javascript. Most of the code is actually for handling the callSuper functionality (calling an overridden method in the super class). The actual subclassing code could be reduced to 4 lines if that bit were removed. Just highlights the “are we sure we need this” question. But its DAMN cool…and I had fun, so it was worth the time.

This script requires arguments.callee.caller to work…that is the magic the code uses to figure out where in the prototype chain to begin the search for the super class’ implementation of the method currently being called. There were some minor tweaks I had to do to get it to work in IE, but it works. As a bonus, calling the ‘callSuper’ method from a constructor will work too.

I’ll probably wind up putting this in a library sometime…I just wanted to get it here and get some eyes on it. Enjoy
Update: I removed the code because it looks horrible on here…I’ll upload and provide a link when I have proper access.

Example Code…this is sickeningly basic…but its what I used while I was putting this together. I’m not sure why I didn’t fire up jsunit to do this thing right (tdd). Oh well…I blame the insomnia.


function Shape(){
this.shapeCalled = true;
}
Shape.prototype.toString = function(arg){
return ‘Shape ‘+arg;
}

function Rectangle(){
this.callSuper();
this.rectangleCalled = true;
}
Class.extend(Rectangle, Shape);
Rectangle.prototype.toString = function(){
var mssg = this.callSuper(’test from rectangle’);
return mssg + ‘ : Rectangle’;
}

function Square(){
this.callSuper();
this.squareCalled = true;
}
Class.extend(Square, Rectangle);
Square.prototype.toString = function(){
var str = this.callSuper();
return str + “:Square”;
}

Update: Finally posted the code here: Class.js. Getting a house ready to sell will keep you busy :)

2 Responses to “A Stab At Javascript Inheritance”

  1. troels Says:

    you forgot to post the code. would you mind ?

  2. Ed Says:

    Yeah, ditto.

Leave a Reply