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.

3
  • 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? Commented Aug 31, 2013 at 17:14
  • Related (if that's what you actually wanted, please edit your question so we can simply close it as a dupe): stackoverflow.com/questions/7582001/… Commented Aug 31, 2013 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. Commented Sep 2, 2013 at 16:43

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.