preface

“Copy” literally means copy, so JavaScript copy is assigning a variable to another variable. There are two types of copy in JavaScript: shallow copy and deep copy. The difference between the two is mainly in reference types

Difference between shallow copy and deep copy

Both shallow copy and deep copy assign a variable to another variable. However, when using a reference type, the variable assigned by shallow copy affects the value of the original variable, while deep copy does not. Since reference types store addresses rather than values (see my previous article on JavaScript basics — Data types), changing the value of a reference variable is changing the value stored in the heap, but since both variables are stored addresses, both variables change.

// Through the shallow copy example
let obj1 = {
    name: 'zhangsan'
}
let obj2 = obj1
obj2.name = 'lisi'
console.log(obj1.name) // lisi
console.log(obj2.name) // lisi
Copy the code

Deep copy approach (regardless of stack overflow)

  • JSON conversion

The two main JSON methods, stringify() and parse(), first convert the original object to JSON using json.stringify () and then convert it back using json.parse (). This method has some drawbacks: 1. If the object contains a function, the function cannot be copied. 2. Unable to copy properties and methods on the object prototype chain

let obj1 = {
    name: 'zhangsan'
}
let obj2 = JSON.parse(JSON.stringify(obj1))
obj2.name = 'lisi'
console.log(obj1.name) // lisi
console.log(obj2.name) // zhangsan
Copy the code
  • Recursively

The use of recursive way to the object in the object all traversal, traversal encountered objects on the new open up a piece of memory for storage

/ / copy
function deepCopy(obj{
    if (typeofobj ! = ='object' || obj === null) {
        return obj;
    }
    let result = {};
    if (obj instanceof Array) { result = []; }
    for(var key in obj) {
         The hasOwnProperty() method of Object returns a Boolean value that determines whether the Object contains a specific (non-inherited) property of itself.
        if(obj.hasOwnProperty(key)) { result[key] = deepCopy(obj[key]); }}return result;
}
let obj1 = {
    name: 'zhangsan'
}
let obj2 = deepCopy(obj1)
obj2.name = 'lisi'
console.log(obj1.name) // lisi
console.log(obj2.name) // zhangsan
Copy the code