1. Let's look at an example:
It can be seen that obj1 copies the value of obj, but only references the address. Modifying the value of obj1 also affects the value of obj, and no new object is created.
Shallow copy: pass-by- value for primitive data types , and pass-by-reference copy for reference data types.
Deep copy: pass-by-value for primitive data types, create a new object for reference data types , and copy its contents
obj2= {
name: 'LiLei',
school: 'HBUT',
age: {
age: '3'
},
run: function aa () {console.log(this.name)}
}
The property of the parent object is equal to an array or another An object, then in fact, the sub-object gets only a memory address (obj3.grade===obj2.grade), not a real copy
For the above object, how to implement 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
}
implements a cyclic copy of the array or object properties in the parent object
2.Object.assign (target object, copy source)
In a Vue project being done, Object.assign is frequently used to copy objects.
When the attributes in the source target are all direct types, it is a deep copy; when the source target contains attributes of reference type, it is a shallow copy.
In the example, the attribute grade object of obj2 is only passed by reference and does not implement a real copy.