Clone is to copy the original thing as it is, and the new copy has nothing to do with the previous thing.
A: In JavaScript, if the cloned object is a basic type, we can assign it directly:
var sStr = "Kingwell"; var cStr = sStr; alert (CSTR); // Output Kingwell SSTR = "abc"; alert (CSTR); //
When you assign a value to another variable, the value of that variable is not affected when it is changed.
It is important to note that the copy will copy the value of the A object to B, because it is the basic type, this value no longer points to other places, so when the value of a changes, the value of B will not change, but if the assignment is the object, the case is different, although the value of a is copied to B, but this value points to the The real content is stored in the heap memory, so when a object changes the content, the content of the B point changes.
Two: If it's not the basic type, it's all different:
var aarr = [0,1,2,3]; var m = aarrr; Alert (m); // Output aarr=[1,1,2,3]; Alert (m); // output 1,1,2,3; This value is changed because M is only a reference to Aarr, and if the value of Aarr is changed, then M will change accordingly.
If we want to clone an array, the simplest way:
var aarr = [0,1,2,3]; var m = aarr.slice (0); = [3,2,1,0]; Alert (m); //
We can create a function to clone all objects:
functionClone (obj) {varo; if(typeofobj = = "Object") { if(obj = = =NULL) {o=NULL; } Else { if(objinstanceofArray) {o= []; for(vari = 0, len = obj.length; i < Len; i++) {O.push (Clone (Obj[i))); } } Else{o= {}; for(varJinchobj) {O[j]=Clone (Obj[j]); } } } } Else{o=obj; } returno; }
Three: node cloning:
var p = document.getelementsbytagname ("P") [0]; var cP = P.clonenode (); // clone p node var cP = P.clonenode (true); // clone p node, deep clone, clone node and sub-content under node.
On several cloning (clone) methods in JavaScript