prototypal inheritance

2007-09-29 @ 13:41#

after years of working with javascript classes with a "classical inheritance" mindset (and learning to lower my expectations because of it), i finally understand crockford's notion "prototypal inheritance" - and i *like* it!

here's a simple example:

// extend Object to ease prototypal inheritance
Object.prototype.begetObject = function() {
    function F() {}
    F.prototype = this;
    return new F();
};

// simple class
function Dog(name)
{
    this.name = (name!==undefined?name:'dog');
};

// smarter class
function HungryDog(o)
{
    var bo = o.begetObject();
    
    bo.eat = function()
    {
        alert('eating...');
    }
    
    return bo;
};

// even smarter class
function TrainedDog(o)
{
    var bo = o.begetObject();
	
    bo.sit = function()
    {
        alert('sitting...');
    }
	
    return bo;
};

// show it all works
var td = new TrainedDog(new HungryDog(new Dog('marvin')));
td.sit();
td.eat();
alert(td.name);

a quote from his article on this topic:

The object function untangles JavaScript's constructor pattern, achieving true prototypal inheritance. It takes an old object as a parameter and returns an empty new object that inherits from the old one. If we attempt to obtain a member from the new object, and it lacks that key, then the old object will supply the member. Objects inherit from objects. What could be more object oriented than that?

Prototypal Inheritance in JavaScript by Douglas Crockford

so, by extending Object with a single function (begetObject) crockford has encapsulated the very essence of the default inheritance pattern for javascript. very nice work!

code