Using Class.extend
By including John Resig's code snippet to enable Class-ical inheritance, you could write this as follows :
var ExampleBaseClass = Class.extend({
init : function() {
console.log("Created class");
},
test : function() {
console.log("Testing class"); // Add an un-overridden method, to test inheritance
},
overrideMe : function() {
console.log("Not overridden"); // Add a method to override
}
});
var ExampleSubClass = ExampleBaseClass.extend({
overrideMe : function() {
console.log("Overridden"); // Override the method
}
});
JS Fiddle here http://jsfiddle.net/z4Z7J/, I've put the full code for the implementation of the generic Class function there, so scroll down to see how you'd use it. Normally that would just be included as a seperate JS file.
Its super neat, and handy because it takes all the prototype
calls out and hides them nicely. Passing in the object literal to the extend method also allows us to group the definition of the class nicely so this appeals to folks from a classical OO background.
It goes through some fairly involved work to make instanceof
work (by ensuring prototype chain is correctly maintained), does some slicing and dicing of the object literals and remapping of the this
context. (Take a look at Some Useful References below this answer).
If you don't care about instanceof
you free yourself up a bit and can use alternate patterns, but for the quickest hit to get the extend
functionality, my vote is with John Resig's snippet.
Some Useful References
There are a number of code libraries and snippets that you can use as the basis for implementing a Class-ical type of inheritance pattern in JavaScript. For example the already mentioned John Resig's Class implementation or Dean Edwards' Base.
They're really worth taking a look at and reading through. Another interesting perspective is Douglas Crockford's Classical inheritance in JavaScript.
Especially the part at the end where he says :
I have been writing JavaScript for 8 years now, and I have never once
found need to use an uber function. The super idea is fairly important
in the classical pattern, but it appears to be unnecessary in the
prototypal and functional patterns. I now see my early attempts to
support the classical model in JavaScript as a mistake. ~ Douglas Crockford
So theres a lot to weigh up and a lot of it is highly subjective!