Shallow copy and deep copy for complex reference type data such as Object, array
Simply put: A shallow copy replicates only one layer of properties, while a deep copy recursively replicates all levels of attributes
One, shallow copy
1 function Clone (origin, target) { 2 var result = Target | | {}; 3 var prop in origin) { 4 Target[prop] = Origin[prop]; 5 6 return result; 7 }
If the object's property value is an array or an object, the stored value is actually a memory address;
The original data and the copied data point to the same address and may not be tampered with.
Second, deep copy
Ideas:
Traverse object for (Var prop in obj)
1. Determine if the original value is typeof () object
2. Determine if an array or an object instanceof constructor toString (still correct in the IFRAME parent-child scope)
3. Create a corresponding array or object and then recursively
1 functionDeepclone (origin, target) {2 vartarget = Target | | {},3Tostr =Object.prototype.toString,4ARRSTR = "[Object Array]";5 for(varPropinchorigin) {6 //Determines whether an object contains a specific property of its own7 if(Origin.hasownproperty (prop)) {8 //excludes null for this special object and is a reference type data for the object type9 if(Origin[prop]!==NULL&&typeof(Origin[prop]) = = ' object '){TenTarget[prop] = (Tostr.call (origin[prop]) = = arrstr)? [] : {}; One Deepclone (Origin[prop], Target[prop]); A}Else{ - //copy basic type Data -Target[prop] =Origin[prop]; the } - } - } - returnTarget; +}
The deep copy not only copies the basic type data of the original object, but also copies the reference type data on the original object to the new object recursively. This will not lead to problems with reference type data pointing to the same object.
jquery provides a $.extend ()- Depth Copy method
Shallow copy: $.extend ({}, obj1, obj2);
Deep copy: $.extend (True, obj1, obj2);
Record Dark copy in JavaScript (clone)