I. In JavaScript, if the cloned object is of the basic type, we can assign a value directly:
1 VaRSSTR = "kingwell";2 VaRCSTR =SSTR;3Alert (CSTR );//Output kingwell4SSTR = "ABC";5Alert (CSTR );//Output kingwell;
When a value is assigned to another variable, when the value of that variable changes, the other value will not be affected.
2. If it is not a basic type, it will be all different:
1 VaRRepeated r = [,];2 VaRM =Repeated RR;3Alert (m );//Output 1, 2, 34Repeated r = [,];5Alert (m );//Output 3, 2,; the value is changed, because M is only a reference of R. If the value of R is changed, M will also change accordingly.
If we want to clone an array, the simplest method is as follows:
1 VaRRepeated r = [,];2 VaRM = mirror R. Slice (0);3Repeated r = [,];4Alert (m );//Output 0, 1, 2, and 3. Although the value in reverse R has changed, a new array has been created by using the slice method.
We can create a function to clone all objects:
1 Function Clone (OBJ ){ 2 VaR O; 3 If ( Typeof OBJ = "object" ){ 4 If (OBJ = Null ){ 5 O = Null ; 6 } Else { 7 If (OBJInstanceof Array ){ 8 O = []; 9 For ( VaR I = 0, Len = obj. length; I <Len; I ++ ){ 10 O. Push (clone (OBJ [I]); 11 } 12 } Else { 13 O = {}; 14 For ( VaR J In OBJ ){ 15 O [J] = Clone (OBJ [J]); 16 } 17 } 18 } 19 } Else { 20 O = OBJ; 21 } 22 Return O; 23 }
Iii. node cloning:
1 var P = document. getelementsbytagname ("p") [0 ]; 2 var CP = P. clonenode (); /// clone a p node 3 var CP = P. clonenode (true); /// clone a p node, in-depth cloning: Clone the node and its sub-content.