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

后端 未结 11 2492
失恋的感觉
失恋的感觉 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:58

    Here are the steps that happen internally for both calls:
    (Hint: the only difference is in step 3)


    new Test():

    1. create new Object() obj
    2. set obj.__proto__ to Test.prototype
    3. return Test.call(obj) || obj; // normally obj is returned but constructors in JS can return a value

    Object.create( Test.prototype )

    1. create new Object() obj
    2. set obj.__proto__ to Test.prototype
    3. return obj;

    So basically Object.create doesn't execute the constructor.

提交回复
热议问题