Prototypal Inheritance Crockford
Prototypal Inheritance Crockford
html
Five years ago I wrote Classical Inheritance in JavaScript (Chinese Italian Japanese). 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.
My journey was circuitous because JavaScript itself is conflicted about its prototypal
nature. 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()
1 of 2 6/19/2020, 8:21 PM
Prototypal Inheritance https://crockford.com/javascript/prototypal.html
efficient. The classical object model is by far the most popular today, but I think that the
prototypal object model is more capable and offers more expressive power.
Learning these new patterns also made me a better classical programmer. Insights from
the dynamic world can have application in the static.
2006-06-07
newObject = oldObject.begetObject();
2007-04-02
The problem with the object function is that it is global, and globals are clearly
problematic. The problem with Object.prototype.begetObject is that it trips up
incompetent programs, and it can produce unexpected results when begetObject is
overridden.
So I now prefer this formulation:
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
newObject = Object.create(oldObject);
2008-04-07
2 of 2 6/19/2020, 8:21 PM