Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 902
madox2 Avatar asked Jan 17 '16 12:01

madox2


People also ask

What is the difference between creating an object using new () and create () methods?

create() is factory construction. You are delegating new() to the factory - the factory looks for overrides and replaces construction of your class with some other derived class. You should always use create() rather than using new() for classes registered with the factory.

What is object assign ()?

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

Why would you use the object create () method to create an object?

The Object. create() method creates a new object, using an existing object as the prototype of the newly created object.


1 Answers

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 } 
like image 57
Oriol Avatar answered Sep 22 '22 04:09

Oriol