javascript deep copy using JSON

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

You can do it that way, but it's problematic for some of the reasons listed above:

  1. I question the performance.

  2. Do you have any non-serializable properties?

  3. And the biggest: your clone is missing type information. Depending upon what you're doing, that could be significant. Did the implementor add methods to the prototype of your original objects? Those are gone. I'm not sure what else you'll lose.