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
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)