2

How come I can store an object as it's own property? Here is a simple example:

let obj = {};
obj['obj'] = obj;

This will result in having an infinite object tree: I can call obj with obj.obj.obj.obj or even with obj.obj.obj.vobj.obj.obj.obj.obj.

Is this an issue for performance? It doesn't seem to bother the browser at all.

Actually, when I look at the console in Chrome and click to expand obj's properties it says (on the tooltip of i):

Value below was evaluated just now

So they were evaluated just when I clicked to expand.

enter image description here

Does this mean that JavaScript too will not look at obj's property until I actually access them?

Is obj.obj just a reference to obj?

Ivan
  • 34,531
  • 8
  • 55
  • 100
  • 3
    I think you need to read up on the concept of "references". The object is not stored inside itself. It contains a _reference_ to itself. – JLRishe Jun 09 '18 at 12:20
  • 1
    _"Is obj.obj just a reference to obj"_ yes. Window and various other objects also have self references. `window.window.window`, `window.top.top.top` etc all just references to the same object – Patrick Evans Jun 09 '18 at 12:23
  • You can check this answer on [what value was evaluated just now means](https://stackoverflow.com/questions/44362783/weird-behaviour-of-console-log-with-javascript-object/44362860#44362860) – Shubham Khatri Jun 09 '18 at 12:23
  • Thank you all for your help. – Ivan Jun 09 '18 at 12:50

1 Answers1

2

Is this an issue for performance?

No. A circular reference is just as every other reference. Every class instance has actually a circular reference:

instance.constructor.prototype.constructor.protototype

Is obj.obj just a reference to obj?

Yes.

Does this mean that JavaScript too will not look at obj's property until I actually access them?

Yes. And the console won't try to expand it as it would get caught up in an endless loop.

Ivan
  • 34,531
  • 8
  • 55
  • 100
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • This is fun and it just happened to me. I tried expanding the obj in Firefox and it only went for around 30 times, and then the obj disappeared. – aryankarim Aug 09 '22 at 07:24