Reputation: 2235
If I make an object, and then set another variable equal to that object, it's just a pointer to the original object. Is there a way to tell if a variable is just a reference, and if so, determine the original variable name?
E.g if I want to json encode an object that has a property that references back to the original object, it creates an infinite loop. I'd like to test if a property is a reference and if so just mark it as such, without rewriting the same object.
Upvotes: 2
Views: 2416
Reputation: 318518
var foo = {'some': 'object'};
var bar = foo;
After this, foo
and bar
are exactly the same as in "they both point to the same object". But besides that there is no relationship between foo
and bar
, so bar
is not a reference to foo
but to the same object. So the answer is "no" since JavaScript does not have references to other variables.
However, to check for circular dependencies - which is what you actually need/want in your example - there are various other, more appropriate, solutions available this question: Is there a way to test circular reference in JavaScript?
Additionally, native JSON encoding using JSON.stringify()
already checks for this:
>>> var obj = {};
>>> obj.x = obj;
>>> JSON.stringify(foo)
TypeError: cyclic object value
Upvotes: 9