javascript - 'Object.assign' mutates state in deeper levels -
i have sample jsbin code @ http://jsbin.com/givolafala/edit?html,js,console,output
var oldobject = { name: 'john', address: { city: 'new york'}}; var newobject = object.assign({}, oldobject); console.log(oldobject); console.log(newobject); newobject.name = 'mathew'; newobject.address.city = 'los angeles'; console.log(oldobject); console.log(newobject);
in example, i'm changing name @ top level john
mathew
. object.assign
returns new state new name mathew
. oldobject
keeps previous value john
.
if change value in level other root, not work. in example change city los angeles
, , notice newobject
, oldobject
have same city los angeles
. oldobject
state mutated.
is bug?
this not bug, called reference. there's difference between how primitive values , objects (references objectes actually) behaves.
var oldobject = { name: 'john', address: { city: 'new york'}};
oldobject
consist of:
name
string value (primitive)addres
object,oldobject
has referenceaddress
object
now:
var newobject = object.assign({}, oldobject);
after copying newobject
has name
value , address
reference
newobject.name = 'mathew';
here change value of newobject
's property.
newobject.address.city = 'los angeles';
but here change property of object newobject
references. reference in oldobject
change oldobject
too.
basically both newobject
, oldobject
have reference same same address
object.
what expected achieve called deep copy.
Comments
Post a Comment