In JavaScript, the assignment between all object variables is an address, and there may be a homecoming asking which objects are object. For example, it might be better to say:
Copy Code code as follows:
typeof (True)//"Boolean"
typeof (1)//"number"
typeof ("1")//"string"
typeof ({})//"Object"
typeof ([])//"Object"
typeof (NULL)//"Object"
typeof (Function () {})//function
So in fact, we deeply copy the main object to be processed is object, non object object as long as the direct normal assignment is good. I realize JS deep copy of the idea is:
Iterate through all of the properties of the object,
If the attribute is "object", special handling is required.
If the object is special and is an array, create a new array and deep copy the elements in the array
If the object is a non-array object, then recursively call the deep copy method directly.
If it is not "object", then the normal copy is done directly.
Here's what I've achieved:
Copy Code code as follows:
Object.prototype.DeepCopy = function () {
var obj, I;
obj = {};
For (attr in this) {
if (This.hasownproperty (attr)) {
if (typeof (this[attr]) = = = "Object") {
if (this[attr] = = null) {
OBJ[ATTR] = null;
}
else if (Object.prototype.toString.call (this[attr]) = = ' [Object Array] ') {
OBJ[ATTR] = [];
For (i=0 i<this[attr].length; i++) {
Obj[attr].push (This[attr][i]. Deepcopy ());
}
} else {
OBJ[ATTR] = this[attr]. Deepcopy ();
}
} else {
OBJ[ATTR] = this[attr];
}
}
}
return obj;
};
If the browser supports ECMAScript 5, for deep copying of all attributes of the object's properties, you can use the
Copy Code code as follows:
Object.defineproperty (obj, attr, Object.getownpropertydescriptor (this, attr));
To replace
Copy Code code as follows:
The benefit of implementing this method directly on Object.prototype is that all objects inherit the method. The downside is that some libraries also overwrite object objects, so conflicts sometimes occur. This is a need for attention. The specific use of the following methods:
Copy Code code as follows:
Object.prototype.DeepCopy = function () {...}
var a = {x:1};
var B = A;
var c = a.deepcopy ();
a.x = 2;
b.x = 3;
Console.log (a.x); 3
Console.log (b.x); 3
Console.log (c.x); 1
The above is about the deep copy of the explanation, but today since we speak of deep copy, then want to correspond to a shallow copy, we will simply sum up the similarities and differences between them.
Shallow copy (Shadow clone): Only the base type of the object is copied, the object type, and still belongs to the original reference.
Deep copy (Depth clone): The base class of the object is not tightly copied, and the objects in the original object are copied. That is, it is entirely a new object.