Helma Logo
main list history
previous version  overview  next version

Version 6 by zumbrunn on 26. March 2007, 15:53

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'|JavaScript Inheritance Sugar* and *Jürg's|JavaScript Inheritance Sugar - Lehni* suggestions for improvements to Dean Edwards' *Base Class|http://dean.edwards.name/weblog/2006/03/base/* 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:

<% this.attachments %>

Mocha Inheritance does its magic in these 20 lines of code:

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])obj[method]
          return     && that.prototype[method]prototype[method] != arguments.apply(obj,args);callee.caller)
       that =     that.prototypeprototype[method].constructor;__parent = that;
            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.


     removed
     added