I have a question about the following canonical object.create method:
Object.create = function(o, props) {
function F() {}
F.prototype = o;
if (typeof(props) === "object") {
for (prop in props) {
if (props.hasOwnProperty((prop))) {
F[prop] = props[prop];
}
}
}
return new F();
};
On line 3 of the above code we set the prototype property of the F object to the o argument’s prototype.
I would have thought this meant that both o and F point to the same prototype and therefore point to the same set of members.
But the code then goes onto copy all the members in the prop in props loop.
What is the point of setting the prototype in line 3 if we then go onto copy all the members manually?
There’s a mistake in the version of
Object.createin your question: The loop attaches the properties to the constructor functionF(not to the returned object, or its prototype) which means they’re not accessible in the created object.The properties of the second parameter to
Object.createare supposed to be copied to the newly created object. The Mozilla documentation forObject.createputs it like this:Try running the following code with the version of
Object.createin the question:You’ll find that
o.a == "prototype's a"ando.b == "prototype's b","object's a"is lost.The following version of the function would probably be more useful:
Let’s try it out with the same example:
The new object
ois created with a prototype that has propertiesaandband it’s own propertya.Let’s look at
o.bfirst:o.hasOwnProperty("b")will returnfalse, becauseodoes not have a property calledb. That’s where the prototype comes in; because there is no propertybit is looked up on the prototype, and thereforeo.b === "prototype's b".On the other hand,
o.hasOwnProperty("a")will returntrue, becauseodoes have anaproperty.o.a == "object's a"and nothing is looked up from the prototype.As pointed out in @chuckj’s answer, the correct implementation of
Object.createis more complicated than this. For more details, see John Resig’s post on ECMAScript 5 Objects and Properties.