What is difference between creating object using Object.create() and Object.assign()?

余生颓废 提交于 2019-12-17 23:22:59

问题


Considering following code:

var obj1 = Object.create({}, {myProp: {value: 1}});
var obj2 = Object.assign({}, {myProp: 1});

Is there any difference between obj1 and obj2 since each object has been created in a different way?


回答1:


Let's compare obj1 and obj2 in this code:

var target1 = {}, target2 = {};
var obj1 = Object.create(target1, {myProp: {value: 1}});
var obj2 = Object.assign(target2, {myProp: 1});

Prototypical chain

Object.create creates a new object with the specified [[Prototype]], and Object.assign assigns the properties directly on the specified object:

obj1 !== target1;
obj2 === target2;

The prototypical chains of obj1 and obj2 look like

obj1 --> target1 -->  Object.prototype --> null
obj2 -------------->  Object.prototype --> null

Properties

Object.create defines properties and Object.assign only assigns them.

When creating a property, assignments will create it as configurable, writable and enumerable. When defining a property, you can specify those flags, but by default it's not configurable, nor writable and not enumerable.

Object.getOwnPropertyDescriptor(obj1, 'myProp');
  // { value: 1, writable: false, enumerable: false, configurable: false }
Object.getOwnPropertyDescriptor(obj2, 'myProp');
  // { value: 1, writable: true, enumerable: true, configurable: true }



回答2:


Object.assign() provides shallow copying(Only properties and methods) and it will override the method and property declared. while Object.create() provides Deep copying provides prototype chain.



来源:https://stackoverflow.com/questions/34838294/what-is-difference-between-creating-object-using-object-create-and-object-assi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!