I have the following JavaScript/Angular code:
var a = {};
var b = {};
a.ref = b;
b.ref = a;
angular.copy(a);
When angular.copy
fires, the browser locks up. I'm assuming this is because the copy function is doing a deep copy, and when it starts to copy a's reference of b, it goes into b and then wants to copy its reference of a, thus creating a circular copy, which will never end.
Is this assumption right? If so, is there a way to avoid this? I'm assuming the answer will involve changing the way my data looks, but I'm curious to hear another person's thoughts.
Your assumption is right, the problem is the circular reference. JSON.stringify
will also complain about this structure. jQuery.extend
detects circular references at a very basic level and can handle your basic example here, but jQuery.extend has its own issues as well. If you're already using jQuery, you can just use extend, but otherwise you may want to look at writing something yourself, or you can use this fancy cloneObject
function I found via Google:
https://gist.github.com/NV/1396086
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With