Understanding the difference between Object.create() and new SomeFunction()

后端 未结 11 2612
失恋的感觉
失恋的感觉 2020-11-22 05:05

I recently stumbled upon the Object.create() method in JavaScript, and am trying to deduce how it is different from creating a new instance of an object with

11条回答
  •  渐次进展
    2020-11-22 05:57

    The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.

    Yes, Object.create builds an object that inherits directly from the one passed as its first argument.

    With constructor functions, the newly created object inherits from the constructor's prototype, e.g.:

    var o = new SomeConstructor();
    

    In the above example, o inherits directly from SomeConstructor.prototype.

    There's a difference here, with Object.create you can create an object that doesn't inherit from anything, Object.create(null);, on the other hand, if you set SomeConstructor.prototype = null; the newly created object will inherit from Object.prototype.

    You cannot create closures with the Object.create syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.

    Well, you can create closures, e.g. using property descriptors argument:

    var o = Object.create({inherited: 1}, {
      foo: {
        get: (function () { // a closure
          var closured = 'foo';
          return function () {
            return closured+'bar';
          };
        })()
      }
    });
    
    o.foo; // "foobar"
    

    Note that I'm talking about the ECMAScript 5th Edition Object.create method, not the Crockford's shim.

    The method is starting to be natively implemented on latest browsers, check this compatibility table.

提交回复
热议问题