Original: Prototypal Inheritance in JavaScript by Douglas Crockford
In a prototypal system, objects inherit from objects. JavaScript, however, lacks an operator that performs that operation. Instead it has a new operator, such that
new f()
produces a an object that inherits from
f.prototype
Fortunately, it is easy to create an operator that implements true prototypal inheritance:
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.
So instead of creating classes, you make prototype objects, and then use the object function to make new instances. Objects are mutable in JavaScript, so we can augment the new instances, giving them new fields and methods. These can then act as prototypes for even newer objects. We don't need classes to make lots of similar objects.
For convenience, we can create functions which will call the object function for us, and provide other customizations such as augmenting the new objects with privileged functions. I sometimes call these maker functions. If we have a maker function that calls another maker function instead of calling the object function, then we have a parasitic inheritance pattern.
Here is another version of the object() function:
if (! Object.create) {
Object.create = function (o) {
function F() {};
F.prototype = o;
return new F();
};
}
newObject = Object.create(oldObject);
Function.prototype.extends = function(o) {
function F() {};
F.prototype = o;
return new F();
};
var Person = function () {};
Person.extends(Animal);





