Helma Logo
main list history
previous version  overview  next version

Version 2 by zumbrunn on 12. January 2007, 13:18

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(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;
    Constructor.prototype.inherit = fnc.prototype;
    return Constructor;
Function.prototype.applySuper = function(method,obj,args) {
    var that = this;
    do {
      if (that.prototype[method] && that.prototype[method] != obj[method])
      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.