First of all, we need to know that JavaScript in addition to the basic type (number,string,boolean,null,undefined)
is a reference type, it can be said to be JS object.
The assignment of a reference type is actually the assignment of the object to the address pointer in the stack, so that two variables point to the same object, and any operation will affect each other.
Before we go into deep cloning, let's take a look at the following example:
EXAMPLE01:
1 var a = [n/a]; 2 var // A B uses a common reference 3 B.push (4); 4 // [1,2,3,4] 5 // [1,2,3,4]
EXAMPLE02:
1 var a = [n/a]; 2 var b = A; 3 // b A new quote was opened 4 // [1,2,3,4] 5 // [A]
EXAMPLE03:
1 var obj = {2 a:103 }; 4 var obj2 = obj; 5 obj2.a =; 6 // -
EXAMPLE04:
1 varobj = {2A:103 };4 functionCopy (obj) {//a shallow copy, a copy-only layer5 varNEWOBJ = {};6 for(varattrinchobj) {7NEWOBJ[ATTR] =obj[attr];8 }9 returnNEWOBJ;Ten } One varObj2 =copy (obj); Aobj2.a = 20; -alert (OBJ.A);//Ten
EXAMPLE05:
1 varobj = {2 A: {3B:104 }5 }6 functionCopy (obj) {//shallow copy, only one layer is copied7 varNEWOBJ = {};8 for(varattrinchobj) {9NEWOBJ[ATTR] =obj[attr];Ten } One returnNEWOBJ; A } - varObj2 =copy (obj); -OBJ2.A.B = 20; thealert (OBJ.A.B);// -
After reading the above examples, we must have a certain understanding of the JS object reference. Next, we look at JS inside another important application---recursion.
The recursive definition can be divided into two points: (1). The function calls the function itself, executes the recursive action, (2). The last time a termination condition is judged, a return action can be performed.
EXAMPLE06:
1 //Find NX (n-1) x (n-2) x ... x2x12 3 functionTest (n) {4 if(n = = 1){5 return1;6 }7 returnN*test (n-1);8 }9Alert (Test (5));// -
Therefore, the deep copy also uses recursion.
the object's child object is also a reference, so when iterating over the assignment, it is determined whether the child element is an object, and if the child element is an object, continues the traversal assignment of the sub-element.
EXAMPLE07:
1 //Deep Copy2 functionDeepclone (obj) {3 varNEWOBJ = {};4 if(typeofObj! = ' object '){5 returnobj;6 }7 for(varattrinchobj) {8NEWOBJ[ATTR] =Deepclone (obj[attr]);9 }Ten returnNEWOBJ; One } A varobj = { - A: { -B:10 the } - }; - varObj2 =deepclone (obj); -OBJ2.A.B = 20; +alert (OBJ.A.B);//Ten
Deep Clone---JS object reference