Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...