2

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.

juacala
  • 2,155
  • 1
  • 21
  • 22
  • 1
    You can do something else, remember a list of objects you already encoded and then check each one before encoding them. But doesn't `JSON.stringify` take care of what you want? – Ofir Israel Aug 31 '13 at 17:14
  • Related (if that's what you actually wanted, please edit your question so we can simply close it as a dupe): http://stackoverflow.com/questions/7582001/is-there-a-way-to-test-circular-reference-in-javascript – ThiefMaster Aug 31 '13 at 17:16
  • I was interested in the actual question, but one application was the example. I think your answer below addresses the question correctly. – juacala Sep 02 '13 at 16:43

1 Answers1

9
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
Community
  • 1
  • 1
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636