There are only 3 lines of code, and yet I’m having trouble fully grasping this:
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
newObject = Object.create(oldObject);
(from Prototypal Inheritance)
-
Object.create()starts out by creating an empty function calledF. I’m thinking that a function is a kind of object. Where is thisFobject being stored? Globally I guess. -
Next our
oldObject, passed in aso, becomes the prototype of functionF. Function (i.e., object)Fnow “inherits” from ouroldObject, in the sense that name resolution will route through it. Good, but I’m curious what the default prototype is for an object, Object? Is that also true for a function-object? -
Finally,
Fis instantiated and returned, becoming ournewObject. Is thenewoperation strictly necessary here? Doesn’tFalready provide what we need, or is there a critical difference between function-objects and non-function-objects? Clearly it won’t be possible to have a constructor function using this technique.
What happens the next time Object.create() is called? Is global function F overwritten? Surely it is not reused, because that would alter previously configured objects. And what happens if multiple threads call Object.create(), is there any sort of synchronization to prevent race conditions on F?
No, it’s stored on the local scope of the
Object.createfunction, each time you invokeObject.createthis functionFwill be recreated.You could even create a more memory-efficient implementation, by storing
Fon a closure, and reuse it:All objects have an internal property that builds the prototype chain, this property is known as
[[Prototype]], it’s an internal property, although some implementations let you access to it, like mozilla, with theobj.__proto__property.The default
[[Prototype]]when you create a new object, i.e.var obj = {};isObject.prototype.All functions have a
prototypeproperty, this property is used when a function is used as a Constructor, invoked with thenewoperator.A new object instance it’s created behind the scenes, and this object
[[Prototype]]is set to its Constructor’sprototypeproperty.Yes, the
newoperator is essential in this method.The
newoperator is the only standard way to set the[[Prototype]]internal property of an object, if you are curious about how it works, you can give a look to the[[Construct]]internal operation.The next time
Object.createis invoked, a new localFfunction is instantiated only within the scope of the method call, you shouldn’t worry about race conditions.Note that this implementation hardly conforms the
Object.createdescribed in the ECMAScript 5th Edition Specification, in that method, you could pass a property descriptor to initialize the object.All browser vendors are implementing it (already available on Firefox 3.7 alphas, latest Wekit Nightly Builds and Chrome 5 Beta), so I would recommend you at least to check if a native implementation exist before overriding it.