In JavaScript, all assignments between object variables are passed through addresses. Some students may ask which object objects are. It might be better to give an example:
The code copy is as follows:
typeof(true) //"boolean"
typeof(1) //"number"
typeof("1") //"string"
typeof({}) //"object"
typeof([]) //"object"
typeof(null) //"object"
typeof(function(){}) //"function"
So in fact, the object that we need to deal with in-depth copying is the object object, and non-object objects are just assigned directly and normally. My idea of implementing deep replication of js is:
Iterate through all properties of this object,
If the property is "object", special processing is required.
If this object object is special and is an array, then create a new array and deeply copy the elements in the array.
If this object object is a non-array object, then just call the deep copy method recursively on it.
If it is not "object", just copy it normally.
Here is my implementation:
The code copy is 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, you can use it in order to deeply copy all the features of the object properties
The code copy is as follows:
Object.defineProperty(obj, attr, Object.getOwnPropertyDescriptor(this, attr));
To replace
The code copy is as follows:
obj[attr] = this[attr];
The advantage of implementing this method directly on Object.prototype is that all objects inherit the method. The disadvantage is that some libraries will also rewrite Object objects, so sometimes conflicts occur. This needs to be paid attention to. The specific usage method is as follows:
The code copy is as follows:
Object.prototype.DeepCopy = function () { ... }
var a = { x:1 };
var b = a;
var c = a.DeepCopy();
ax = 2;
bx = 3;
console.log(ax); //3
console.log(bx); //3
console.log(cx); //1
The above is an explanation about deep replication. However, since we talked about deep replication today, we want to have shallow replication correspondingly. Let’s briefly summarize the similarities and differences between them.
Shallow copy (shadow cloning): Only copy the basic type of the object and the object type still belong to the original reference.
Deep copy (deep cloning): It does not copy the basic class of the object, but also copies the objects in the original object. That is to say, it is completely generated by the new object.