Clone in IFE_part2_JavaScript_JS (implementation of deep clone)

Understand the concept and difference between easy clone and deep clone in JS:

  • Shallow clone: ​​Primitive types are passed by value, and object types are still passed by reference.
  • Deep clone: ​​All elements or attributes are completely copied and completely separated from the original object, that is, all modifications to the new object will not be reflected in the original object.

    // Shallow clone: ​​primitive types are passed by value, and object types are still passed by reference. / For the shallow clone of the object, when the new object is modified, the properties of the original object will also be modified
    var a="1";
    var b=a;
    b="2";
    console.log(a);// "1"
    console.log(b);// "2"
    
    // Deep clone: ​​All elements or attributes are completely copied and completely separated from the original object, which means that all modifications to the new object will not be reflected in the original object.
    function cloneObject(src) {
        was the result
        if (typeof src == "string" || typeof src == "number") {
            var result = src;
        }
        else if (src instanceof Array == true) {
            var result = src
        }
        else if (typeof src == "object") {
            // Deep clone implementation method 1 / Disadvantages: 1. Cannot copy function 2. The prototype chain is gone, the object is the object, and the class to which it belongs is gone.
            var result = JSON.parse (JSON.stringify(src))
        }
        return result;    
    }
    
    // test case:
    var srcObj = {
        a: 1,
        b: {
            b1: ["hello", "hi"],
            b2: "JavaScript"
        }
    };
    var abObj = srcObj;
    var tarObj = cloneObject (srcObj);
    
    srcObj.a = 2;
    srcObj.b.b1[0] = "Hello";
    
    console.log(abObj.a);
    console.log(abObj.b.b1[0]);
    
    console.log(tarObj.a);      // 1
    console.log(tarObj.b.b1[0]);    // "hello"
    

    In addition to the method of JSON.parse (JSON.stringify(src)), there are also methods implemented through Object.assigin and recursion , and the recursive method is currently being understood.

Guess you like

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