1. First look at an example:
As can be seen, obj1 copied the value of obj, but only the address reference, modify the value of OBJ1 also affect the value of obj, did not create a new object.
Shallow copy: A value pass on the base data type , and a reference to the reference data type as a transitive copy.
Deep copy: values are passed to the base data type , a new object is created for the reference data type, and its contents are copied
obj2= {
Name: ' Lilei ',
School: ' Hbut ',
Age: {
Age: ' 3 '
},
Run:function AA () {Console.log (this.name)}
}
The property of the parent object is equal to the array or another object, so actually, the child object obtains only one memory address (Obj3.grade===obj2.grade), not the real copy
For the above object, how to implement a deep copy
function Deepcopy (obj) {
temp = Obj.constructor = = = Array? [] : {}
For (let Val in obj) {
Temp[val] = typeof Obj[val] = = ' object '? Deepcopy (Obj[val]): Obj[val]
}
Return Temp
}
Implementing a circular copy of an array or object property in a parent object
2.object.assign (target object, copy source)
In a Vue project that is being done, object.assign is frequently used to achieve copies of images.
When a property in the source target is a direct type, this is a deep copy, which is a shallow copy when the source target has a property of the reference type.
The Obj2 attribute in the example grade object simply refers to a value and does not implement a true copy.
JavaScript deep copy and shallow copy