JavaScript deep copy vs shallow copy

1. Let's look at an example:
JavaScript deep copy vs shallow copy
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)}
}
JavaScript deep copy vs shallow copy
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
JavaScript deep copy vs shallow 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.

JavaScript deep copy vs shallow copy
In the example, the attribute grade object of obj2 is only passed by reference and does not implement a real copy.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324493453&siteId=291194637