Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a javascript circular reference work?

Tags:

javascript

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?

like image 779
luk3thomas Avatar asked Jan 10 '23 20:01

luk3thomas


1 Answers

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"!

like image 111
Niet the Dark Absol Avatar answered Jan 23 '23 15:01

Niet the Dark Absol