4

I'm not sure why this works.

var a = {};
a.hello = a;

If you explore the object in the console you'll see something like this: enter image description here

a.hello = a is a circular reference. It seems that when we assign a.hello = a everything would blow up. Can someone explain what is happening internally?

2 Answers 2

5

You have a single object.

That object contains a property, which is a pointer to the same object.

That's all.

From there, you can continually recurse into a.hello.hello.hello.hello as much as you like, but you're still just referencing the same object. That is, a.hello === a.hello.hello for any depths.

Given that window behaves in the same way (window.window.window.window.MUSHROOM) it's a good thing it doesn't "blow up"!

Sign up to request clarification or add additional context in comments.

Comments

4

When dealing with objects JavaScript handles them by reference, not as copy. So circular constructs are no problem.

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.