On Classical JavaScript Inheritance 
September 7th, 2006
Ok, I have been a little busy lately (well really busy) but this post has been in the works for a few weeks now so I just want to get it out.
First off, of the half dozen or so requirements that Dean Edwards puts on his Base.js implementation I admittedly only agree with two of them - and you should see why at the end of this post. Those two are:
I want to avoid calling a class’ constructor function during the prototyping phase
I want to achieve the above without affecting Object.prototype
Those are by far the most important points - particular number one since when dealing with the DOM / UI we don’t want things to happen pre-maturely.
Anyway, the reason for this post is actually due to a recent post on Ajaxian about JavaScript inheritance that was interesting to say the least. It reviewed a few different techniques of performing classical inheritance in the prototype base language that is JavaScript. It reviewed simple inheritance using the syntax like
where super methods can be called using global references to the BaseClass from the SubClass and call or apply such as
The author also looked at the more advanced technique from Douglas Crockford and finally showed his preferred method.
There are a few points that I would like to add to the discussion. First of all, the authour suggests staying away from syntax such as
this.getName = function() {
return "BaseClass";
};
}
due to the fact that it can cause “SEVERE” memory leaks in Internet Explorer. Closures - which is what is used here - are one of the most useful features of JavaScript and should not be avoided but instead embraced. Indeed, if you lose references to DOM elements in your closures without removing them you can get memory leaks. Whether or not the leak is severe depends on how much memory is taken up by your DOM references of course. Just because something is dangerous does not mean it should be avoided - I am not going to stop drinking scotch any time soon
I also thought that the example he gave to show how the Crockford method is broken was a bit strange. Admittedly, it does seem that the alert from the Crockford method is not correct being (2-1-1), however, I don’t think that the alert from the authors code is correct either. The numbers I would expect to see would be (2-2-1). In fact, with no polymorphism, overrides or other method metadata, who is to really say how it should work?
There were also two very important inheritance techniques that I thought should have certainly been mentioned. One important technique is that developed by Dean Edwards, which _very_ nicely emulates the usage of the super keyword in Java (although he uses base since super is reserved) to provide access to the BaseClass. If you are interested in the Dean Edwards code go check out his blog. The other is the use of global references that refer not to the BaseClass, as the authour showed in his article, but instead to the SubClass; thus, we avoid any problems one may have with making explicit references to the BaseClass within the SubClass code. We can define a global function that extends a SubClass that looks something like this:
/**
* Allows support for inheritance.
* @param subClass {object} The class that will inherit from the base.
* @param baseClass {object} The class that will be inherited from.
*/
nitobi.extend = function(subClass, baseClass)
{
// Create a new class that has an empty constructor
// with the members of the baseClass
function inheritance() {};
inheritance.prototype = baseClass.prototype;
// set prototype to new instance of baseClass
// _without_ the constructor
subClass.prototype = new inheritance();
subClass.prototype.constructor = subClass;
subClass.baseConstructor = baseClass;
// enable multiple inheritance
if (baseClass.base)
{
baseClass.prototype.base = baseClass.base;
}
subClass.base = baseClass.prototype;
}
This is similar to the method over on Kevlindev. Btw, discussion about all of these techniques can be found before the Crockford technique when Googling for “JavaScript inheritance”. I digress. We have also added the prototype chain support for the
nitobi.extend(SubClass, BaseClass);
Methods in the BaseClass are then called like this:
Not only is this, IMHO, a clearer syntax than something more esoteric like “arguments.callee.$” but it also has the added advantage of being faster - as I will show in a moment - than something more complicated like being able to use the word “base” directly. Furthermore, by using the Prototype library syntax for defining functions where the prototype of an object is set to an inline object itself such as:
someMethod: function() {},
someProperty: 5
});
it makes it much more difficult to document using tools such as JSDoc. I always find myself missing commas too! Personally, I find the Prototype syntax much more unfriendly, although it is slightly more terse.
As for the performance, just to give an idea of how the different techniques fair I made a simple animal inheritance chain and checked that the inheritance works properly using each method and then measured 1000 class definitions and instantiations with a call to the super / base in the constructors. It was some nonsense like this:
function Animal(name) {
this.name = name;
};
Animal.prototype.name = "";
Animal.prototype.eat = function() {
this.say("Yum!");
};
Animal.prototype.say = function(message) {
alert(this.name + ": " + message);
};
function Cat()
{
Cat.baseConstructor.call(this, 'cat');
}
nitobi.extend(Cat, Animal);
Cat.prototype.eat = function(food) {
if (food instanceof Mouse) Cat.base.eat.call(this);
else this.say("Yuk! I only eat mice - not " + food.name);
};
function Lion()
{
Lion.baseConstructor.call(this, 'lion');
}
nitobi.extend(Lion, Cat);
Here is what I found for performance using various techniques:
Internet Explorer
| Approach | Time | Relative |
| Nitobi | 320 | 1 |
| Crockford | 340 | 1.06 |
| ThinWire | 580 | 1.81 |
| Edwards | 1360 | 4.25 |
Firefox
| Approach | Time (ms) | Relative |
| Nitobi | 360 | 1 |
| Crockford | 460 | 1.27 |
| ThinWire | 2300 | 6.39 |
| Edwards | 3600 | 10 |
I was pretty surprised at the horrible performance of the Edwards base.js in Firefox! At any rate, something to consider for those that do things because they want JavaScript to be more like Java
technorati tags:ajax, javascript, performance, benchmark, inheritance, oop
