I'd like to know what you think about my implementation of inheritance. It's pretty small and intuitive I think, but I don't know if there are any drawbacks.
I really want to keep it as simple as possible, therefore I don't want to use any libraries.
Actual code:
Object.prototype.__extends = function __extends(parent){
var child = this;
if(parent){
child.prototype = new parent();
child.prototype.__super = function __super(){
if(child.prototype[arguments.callee.caller.name]){
return child.prototype[arguments.callee.caller.name].apply(this,arguments);
}else{
return child.prototype.constructor.apply(this,arguments);
}
}
}
return child;
}
Usage:
function Parent(args) {
// set up Parent class
this.someFunction = function someFunction(args){
// do something
}
}
Child = function Child(args){
this.__super(args); // not needed if parent constructor has no arguments
// set up child class
this.someFunction = function someFunction(args){ // no anonymous function here!
this.__super(args); // calls Parent.someFunction !
// do something else
}
}.__extends(Parent); // This is where the magic happens
child = new Child(args);
Example on JSFiddle
Update
I wanted to add some information on why I pursued this approach and what is actually happening in the code.
I originally created this code to have a way of inheritance that resembles inheritance in other languages (primarily Java) and is therefore easy to understand for most people.
I know it's not thought of as best-practice to inherit from functions via the new
keyword but in this special case, where it should feel more like Java, I think this was the way to go. And if I recall correctly frameworks like prototype.js do so as well.
What annoyed me the most in classical inheritance in JavaScript was that everything was decentralized. First you define your constructor function, then you define the methods for you parent class and later you describe the inheritance.
I wanted to give JavaScript inheritance the feeling of classes.
Description
As anyone probably sees on first sight, I'm doing something evil here. I'm extending the Object prototype. I could have extended the Function prototype instead of the Object prototype but I don't think this is less evil.
What the __extends
function does is, it creates a new instances of the parent object in order to use it as the prototype of the child. The new
keyword enables us to write classes in the way I did above.
Additionally the child gets the __super
function which is used to reference the parents functions.
If the caller of the __super
function doesn't have a counterpart (same name) on the parent side, the parents constructor
is called. If there is indeed a counterpart, it is called.
The arguments given to the __super
function are redirected to the function that really should be called using .apply()
.
The return child
at the end is needed to be able to put the .__extends()
on the end of your "class" definition.