Search code examples
javascriptprototypal-inheritance

What is Object.Create() doing under the hood?


I'm diving more into Prototypal Inheritance with JavaScript. When Object.Create() is in use to create objects, can someone show what is going on under the hood? Does Object.Create() depend on new and constructor functions behind the scenes?


Solution

  • When Object.create() is in use to create objects, can someone show what is going on under the hood?

    Low level details. Object.create is pretty much a primitive operation - similar to what happens when an {} object literal is evaluated. Just try to understand what it is doing.

    That said, with new ES6 operations it could be implemented in terms of

    function create(proto, descriptors) {
        return Object.defineProperties(Object.setPrototypeOf({}, proto), descriptors);
    }
    

    Does Object.create() depend on new and constructor functions behind the scenes?

    No, not at all. It's the reverse rather. The new operator could be implemented as

    function new(constructor, arguments) {
        var instance = Object.create(constructor.prototype);
        constructor.apply(instance, arguments);
        return instance;
    }