Javascript inheritance
When it comes to web development, Javascript is the best client-side programming language. It has come a long way in the last years. It’s no longer just a simple scripting language. These days a lot of Javascript libraries are available to be used freely and they are incredibly powerful: Script.aculo.us, DOJO, YUI, jQuery, Prototype, to name just a few.
I am personally not very found of Javascript because of its loosely typed nature. I consider it harder to develop a large framework in Javascript compared to say, Java, because the compiler/interpreter cannot always come to your rescue as you’d expect if you’re coming from a strongly typed language.
But a lot of its strength comes from the fact that it’s loosely typed. You also feel the sense of freedom that only these kind of languages (like Ruby) can offer. Types help you a lot to avoid errors and to give you important structure, but also constrain your ability to do more with your code.
Javascript is (or can act like) a(n almost) full fledged object oriented language. Let’s try inheritance:
This is the method that simulates inheritance in Javascript:
function inherit(child, parent) {
var sConstructor = parent.toString();
var aMatch = sConstructor.match( /\s*function (.*)\(/ );
if ( aMatch != null ) { child.prototype[aMatch[1]] = parent; }
for (var m in parent.prototype) {
child.prototype[m] = parent.prototype[m];
}
};
Let’s define some Javascript objects:
function Element() {
this.location = null;
this.type = "Element";
this.selected = false;
this.zIndex = 0;
}
Element.prototype.isInside = function(rectangle){
dosomething;
}
function Item() {
this.Element(); //calling the constructor of the base class
this.lastValidLocation = null; //a rectangle
this.type = "Item";
this.selectorItem = null;
this.zIndex = 1;
}
inherit(Item, Element);
Item.prototype.getSelectorItem = function() {
return this.selectorItem;
}
Item.prototype.draw = function() {
dosomething;
}
Item.prototype.deleteItem = function() {
dosomething;
}
function SelectorItem() {
this.Element();
this.items = new Array();
this.type = "SelectorItem";
this.zIndex = 0;
}
inherit(SelectorItem, Element);
SelectorItem.prototype.getSelectorItem = function() {
return this;
}
SelectorItem.prototype.createNewItem = function(onItem) {
dosomething;
}
SelectorItem.prototype.draw = function() {
dosomething;
}
It is very important when you call “inherit”. That’s because Javascript does not support method override/overload, but you can also simulate this. When executing “inherit”, the prototype of the base class will be copied to the child. Then, if needed, redefine some methods so that when you call them, the new ones will get executed.




