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

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

    function Test(){
        this.prop1 = 'prop1';
        this.prop2 = 'prop2';
        this.func1 = function(){
            return this.prop1 + this.prop2;
        }
    };
    
    Test.prototype.protoProp1 = 'protoProp1';
    Test.prototype.protoProp2 = 'protoProp2';
    var newKeywordTest = new Test();
    var objectCreateTest = Object.create(Test.prototype);
    
    /* Object.create   */
    console.log(objectCreateTest.prop1); // undefined
    console.log(objectCreateTest.protoProp1); // protoProp1 
    console.log(objectCreateTest.__proto__.protoProp1); // protoProp1
    
    /* new    */
    console.log(newKeywordTest.prop1); // prop1
    console.log(newKeywordTest.__proto__.protoProp1); // protoProp1
    

    Summary:

    1) with new keyword there are two things to note;

    a) function is used as a constructor

    b) function.prototype object is passed to the __proto__ property ... or where __proto__ is not supported, it is the second place where the new object looks to find properties

    2) with Object.create(obj.prototype) you are constructing an object (obj.prototype) and passing it to the intended object ..with the difference that now new object's __proto__ is also pointing to obj.prototype (please ref ans by xj9 for that)

提交回复
热议问题