Reputation: 607
I am trying to make an instance of an object. I got a little confused facing Object.assign()
. What's the difference between the below 2 codes?
const obj3 = Object.assign(obj2, obj1);
and:
let obj2: model;
obj2= obj1;
Upvotes: 3
Views: 3224
Reputation: 370729
Assignment only creates another reference to the exact same object in memory. If you assign, then change by referencing one of the variable names, the other one will have changed too, since they're the same thing.
Object.assign
will assign all enumerable own properties of the second (and further) parameters to the first parameter, and will return the first parameter. So
const obj3 = Object.assign(obj2, obj1);
is a bit like
for (const prop in obj1) {
obj2[prop] = obj1[prop]
}
obj3 = obj2;
(with plain objects - skipping the own aspect)
They're quite different.
Upvotes: 6