Shallow copy:
Create a new object that has exactly the same attributes as the original object, but for non-primitive attributes, points to the memory address of the object to which the original attribute points.
Deep copy:
When a new object is created, other objects referenced in the property will be cloned and no longer point to the original object address.
Shallow copy implementation (Object.assign) :
let x = {
a: 1.b: {f: {g:1}},
c: [1.2.3]}let y = Object.assign({},x)
console.log(y.b.f === x.b.f); //true
Copy the code
Deep copy can be implemented in two ways:
Parse (json.stringify (copyObj))
Advantages: Easy to use
Weaknesses:
- If the function in the object, re, date, cannot be copied.
- Unable to copy properties and methods on the copyObj object prototype chain.
- When the data level is very deep, stack overflow occurs.
Method 2: Handwritten copy
“Advantage” : Can consider all situations
“Cons” : Complex implementation
// Write deep copy function
function deepClone(obj) {
if(typeofobj ! = ='object' || obj == null) {
return obj;
}
let objClone;
if(obj instanceof Array) {
objClone = [];
}
else {
objClone = {};
}
for(let key in obj) {
if(obj.hasOwnProperty(key)) {
// If it is still an object, recurse
if(obj[key] && typeof obj[key] === "object") {
objClone[key] = deepClone(obj[key]);
} else{ objClone[key] = obj[key]; }}}return objClone
}
/ / test
let person = {
name: 'zhangsan'.friends: {
name: 'lisi'}}let person2 = deepClone(person)
person2.friends.name = 'wangwu'
console.log(person);
console.log(person2);
Copy the code