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?
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?
On
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.
I have created a whole medium page on exactly how each data type reacts on Shallow copy and Deep copy.
Here is the link: https://siddharthsunchu1.medium.com/copies-of-javascript-shallow-and-deep-copy-ac7f8dcd1dd0
On
you can also combine them Object.assign(Object.create(object)) for both shallow and deep copy, they are perfectly valid pattern in ES6.
On
we can also create deep copy of object like this
var obj = {id:1, fname:'sajid', lname: 'imtiaz'};
var deepObj = Object.assign({},obj)
`
Let's compare
obj1andobj2in this code:Prototypical chain
Object.createcreates a new object with the specified [[Prototype]], andObject.assignassigns the properties directly on the specified object:The prototypical chains of
obj1andobj2look likeProperties
Object.createdefines properties andObject.assignonly 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.