Reputation: 115
This strange phenomenon I've encountered here may have a specific name, which may be why I couldn't find anything about it on Google.
I was working on my project, and I found a strange object in my inspector. My code is broken in many files, and there are many things happening at the same time so I didn't immediately notice, but when I opened my object, I discovered that it was infinite.
I will try to reproduce here what i did:
var monkey = {dad: 1, son: 1, have: null};
var banana = {state: 1, eatable: 1, have: null};
monkey.have = banana;
banana.have = monkey;
console.log(monkey);
If you inspect "monkey" object, and expand the 'have' prop, you will see that it never ends. Because banana always have monkey and monkey always have banana, recursively.
(I think this is probably due to the fact that javascript always passes reference to objects instead of the real value.)
I've seen this in other languages, but it always prevented execution and raised an explicit error.
Why doesn't that happen with javascript? And, more worrying, is this kind of code dangerous in any way?
Thanks for your help!
Upvotes: 3
Views: 129
Reputation: 16585
Two object instances, two references stored, that's all. There's no risk for memory leaks whatsoever because nothing is being copied, it just gives the "illusion" of being infinite, but it's always pointing to the same objects and the same memory allocated for them.
Upvotes: 1
Reputation: 35407
The following snippet exemplifies that both properties reference the same instance:
var monkey = { name: "monkey boy", son: 1 };
var banana = { name: "ripe banana", eatable: 1 };
monkey.eats = banana;
banana.eatenby = monkey;
console.log(monkey);
/* alerts "monkey boy" - original monkey instance */
alert(monkey.eats.eatenby.eats.eatenby.name);
Notice that when you continue to "drill-down" through the properties, the references to the original objects are maintained (values are the same).
Upvotes: 2
Reputation: 4003
It's called a circular reference, and it does cause issues (leaks) in some browsers. Usually in IE, when an object has a circular reference to a DOM object (and the DOM element is removed) causes a memory leak. Most modern browsers account for this pattern.
Upvotes: 2
Reputation: 224983
Modern browsers' garbage collectors are smart and can detect objects that are only kept alive by a circular reference and dispose of both of them. A lot of languages do this; all the .NET ones, Java, Ruby, Python... it's not so difficult to implement.
Upvotes: 2