Anders Engblom discovered a problem with the applySuper method in version 0.2 of my mocha-inheritance code. The applySuper method wasn't properly keeping track of the prototype chain in cases where it inherited a method that itself called applySuper again. The best solution that I can think of so far is to add a "__parent" property to the inherited method, which points to the constructor that defined it.
So, here is the updated version:
/** * Mocha Inheritance -- Javascript prototype inheritance reduced to the max. * * Chris Zumbrunn chris@zumbrunn.com http://zumbrunn.com * version 0.3, March 26, 2007 */ Function.prototype.inherit = function(fnc) { var constr = this; var Constructor = function(){ if (fnc) fnc.apply(this, arguments); constr.apply(this, arguments); }; Constructor.prototype = new (fnc || this)(); Constructor.prototype.constructor = fnc || this; return Constructor; }; Function.prototype.applySuper = function(method,obj,args) { var that = arguments.callee.caller.__parent || this; do { if (that.prototype[method] && that.prototype[method] != obj[method] && that.prototype[method] != arguments.callee.caller) { that.prototype[method].__parent = that; return that.prototype[method].apply(obj,args); } that = that.prototype.constructor; } while (that != Object); };
Example page and code with some additional syntactic sugar:
mocha.js | application/x-javascript | 1735 bytes |
mocha.html | text/html | 1942 bytes |
See the Mocha Inheritance wiki page on the Helma site for more details and to provide your comments.
28.3.2007, 0:15