Wednesday, August 23, 2006

Crockford on Prototypal Inheritance

Douglas Crockford has put up this intriguing page on Prototypal Inheritance in JavaScript:

Five years ago I wrote Classical Inheritance in JavaScript. It showed that JavaScript is a class-free, prototypal language, and that it has sufficient expressive power to simulate a classical system. My programming style has evolved since then, as any good programmer's should. I have learned to fully embrace prototypalism, and have liberated myself from the confines of the classical model.

. . .

Fortunately, it is easy to create an operator that implements true prototypal inheritance. It is a standard feature in my toolkit, and I highly recommend it for yours.


function object(o) {
function F() {}
F.prototype = o;
return new F();
}


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?


It makes sense that since JavaScript is a prototype-based OOP language, its prototyping support should be exploited directly, not used to simulate something we are more used to (here, class-based OOP).

No comments: