In JavaScript, all assignments between object variables pass addresses. Some students may ask which objects are objects. It might be better to give an example:
So in fact, the main object we need to process in deep copy is the object object. Non-object objects only need to be assigned directly and normally. My idea of implementing js deep copy is:
Traverse all the properties of the object,
If the attribute is "object", special handling is required,
If this object is special and is an array, then create a new array and deeply copy the elements in the array
If this object is a non-array object, just call the deep copy method recursively on it.
If it is not "object", just copy it normally.
The following is my implementation:
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
}
} else {
obj[attr] = this[attr].DeepCopy();
}
} else {
obj[attr] = this[attr];
}
}
}
Return obj;
};
If the browser supports ECMAScript 5, in order to deep copy all properties of the object properties, you can use
to replace
The advantage of implementing this method directly on Object.prototype is that all objects will inherit this method. The disadvantage is that some libraries also rewrite Object objects, so conflicts sometimes occur. This is something to note. The specific usage methods are as follows:
The above is the explanation about deep copy, but since we talked about deep copy today, we also want to correspond to shallow copy. Let’s briefly summarize the similarities and differences between them.
Shallow copy (shadow clone): Only the basic type and object type of the object are copied, which still belongs to the original reference.
Deep copy (deep clone): not only copies the basic class of the object, but also copies the objects in the original object. That is to say, completely new objects are generated.