I just got Javascript: The Good Parts by Douglas Crockford and I’m having some difficulty understanding one of his examples regarding prototypes. The code in the book reads as follows:
if (typeof Object.create !== "function") {
Object.create = function(o) {
var F = function () {}
F.prototype = o;
return new F;
};
}
I’m assuming that this code is used to target a function’s prototype. But why use such a complex approach? Why not just use variable.prototype? Crockford is the leading expert on Javascript so I’m sure there is a good reason for using this model. Can anyone help me understand it better? Any help would be appreciated.
In ECMAScript 3, the
newoperator was the only standard way to set the[[Prototype]]internal property of an object, in this case, Crockford is just using a temporary constructor functionFfor that purpose.The
oargument of that method, is set as theprototypeproperty of the temporary constructor, and by invokingnew F();it builds a new empty object that inherits fromF.prototype(see this question for more details about hownewworks).For example:
In the above example, we can say that the
b‘s internal[[Prototype]]property points toa.In other words,
binherits froma.With the same example, we could use an empty constructor, e.g.:
Remember also that the
prototypeproperty of functions is different than the[[Prototype]]property that all objects have, theprototypeproperty of functions is used when they are called with the new operator, to build a new object that inherits from that property.Also, be aware that now, the ECMAScript 5 Standard is being implemented, and this shim, doesn’t conform 100% with the spec, in fact, there are some features of the standard
Object.createmethod that cannot be emulated on ES3.See also: