Js deep copy VS shallow copy strange image, seek explanation

changed the original object
obj1 = {a:1,b:{b1:1}}
obj2 = Object.assign({},obj1)
obj2.b.b1=2
console.log(obj1.b.b1)// 2
obj1 = {a:1,b:{b1:1}}
obj2 = Object.assign({},obj1,{})
obj2.b.b1=2
console.log(obj1.b.b1)// 2
the original object has not been changed
obj1 = {a:1,b:{b1:1}}
obj2 = {a:2,b:{b1:2}}
obj3 = Object.assign({},obj1,obj2)
obj3.b.b1=8
console.log(obj1.b.b1)// 1
Nov.26,2021

if the attribute in the target object has the same key, the attribute will be overwritten by the attribute in the source. The properties of later sources will similarly override the previous properties.

Menu