What is happening in Crockford's object creation technique?

Posted by Chris Noe on Stack Overflow See other posts from Stack Overflow or by Chris Noe
Published on 2010-05-04T14:18:10Z Indexed on 2010/05/04 14:28 UTC
Read the original article Hit count: 234

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)

1) Object.create() starts out by creating an empty function called F. I'm thinking that a function is a kind of object. Where is this F object being stored? Globally I guess.

2) Next our oldObject, passed in as o, becomes the prototype of function F. Function (i.e., object) F now "inherits" from our oldObject, 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?

3) Finally, F is instantiated and returned, becoming our newObject. Is the "new" operation strictly necessary here? Doesn't F already 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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about prototypal-inheritance