In its current incarnation, Javascript prototype inheritance has some shortcomings. In particular, prototypes do not inherit their parent's constructor and methods in child prototypes can not dynamically access an inherited method they override.
After Hannes' and Jürg's suggestions for improvements to Dean Edwards' Base Class approach to Javascript inheritance, I made an attempt to solve the problem by focusing more intensely on fixing Javascript's prototype inheritance than adding class sugar around it.
What I came up with is this:
name | type | size |
mocha.js | application/x-javascript | 1311 bytes |
mocha.html | text/html | 1942 bytes |
Mocha Inheritance does its magic in these 20 lines of code:
Function.prototype.inherit = function(inherit) { var fnc = inherit ? this : function(){}; inherit = inherit || this; var Constructor = function(){ inherit.apply(this, arguments); fnc.apply(this, arguments); }; Constructor.prototype = new inherit(); Constructor.prototype.constructor = inherit; return Constructor; }; Function.prototype.applySuper = function(method,obj,args) { var that = this; do { if (that.prototype[method] && that.prototype[method] != obj[method]) return that.prototype[method].apply(obj,args); that = that.prototype.constructor; } while (that != Object); };
Creating a new prototype "Mensch" with mocha inheritance from "Animal":
var Mensch = Animal.inherit();
Letting a previously created constructor "Mensch" mocha inherit from "Animal":
Mensch = Mensch.inherit(Animal);
And here an example of a Mensch method "evolve" that overrides what it inherits from Animal, but still manages to do nothing different:
Mensch.prototype.evolve = function(){ return this.constructor.applySuper('evolve', this, arguments); }
With some more syntactic sugar around it, I think this is quite a nice approach.
http://dev.helma.org/wiki/Mocha+Inheritance/
12.1.2007, 13:20