If your object is "small" and contains exclusively serializable properties, a simple deepCopy hack using JSON serialization should be OK. But, if your object is large, you could run into problems. And if it contains unserializable properties, those'll go missing:
var o = {
a: 1,
b: 2,
sum: function() { return a + b; }
};
var o2 = JSON.parse(JSON.stringify(o));
console.log(o2);
Yields:
Object {a: 1, b: 2}
Interestingly enough, a fair number of deep-copy solutions in C# are similar serialization/deserialization tricks.
Addendum: Not sure what you're hoping for in terms of comparing the objects after the copy. But, for complex objects, you generally need to write your own Compare()
and/or Equals()
method for an accurate comparison.
Also notable, this sort of copy doesn't preserve type information.
JSON.parse(JSON.stringify(new A())) instanceof A === false
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…