Before writing JS More of the time also written deep copy, shallow copy, inherit what, there are custom monitoring events. But it took a long time to forget.
The most recent deep copy used in the project is B = Json.parse (Json.stringify (a)), did not delve into the principle, and did not consider hundred percent correctness. It's just a lot of mistakes.
But when someone in the group asked how to make a deep copy, I threw out this simple method. There is a great God out there to say that this is not true. Instant Meng, after the great God guidance and their popularity. Finally found the pit, a burst of sweating!
The pit point is that if you want a deep copy of the object property value to be undefined or function, it will be filtered out!
1.JSON does not support nan,infinity, even accurate floating-point numbers, let alone circular references and function.
2. Serialization is serialization, deserialization is deserialization, do not misuse.
3. b = JSON.parse( JSON.stringify(a) ) Limitations: Unable to copy function; The prototype chain is gone, the object is objects, the class that belongs to is gone. But he is simple, most of the time can fully meet the demand!
By the way, a good deep copy function is attached.
var a={
M:undefined,
B:2,
c:[1,2,3],
d:[1,[2,3],4],
E:null,
F:function () {
Console.log (' 11 ')
}
}
function Deepcopy (p,c) {
var i;
c = c| | {};
For (I in P) {
if (P.hasownproperty (i)) {
if (typeof (P[i]) = = = = "Object") {
C[i] = Array.isarray (P[i])? []:{};
Deepcopy (P[i],c[i]);
}else{
C[i] = P[i];
}
}
}
return C;
}
var b=deepcopy (B,a)
Console.log (b)
Printing results:
Use the JSON method to make deep copies of something you should know!