I’m learning JavaScript and there’s an example in the book I’m using that I didn’t understand.
It’s like this:
var chineseBox = {};
chineseBox.content = chineseBox;
Then the book lists two expressions and their values. First, "content' in chineseBox; that returns true. Then, the one I don’t get, "content" in chineseBox.content which also returns true.
I think it’d be more natural if the second expression evaluated to false, pointing to the empty chineseBox object defined earlier.
Is there a reason to work like this? What are the practical implications of this feature?
And how do I explore deeper levels of the object? Is chineseBox.content.content right?
It’s not empty anymore. As of
chineseBox.content = chineseBox, it now has a property.When you assign object references to things (variables, properties, etc.), the value stored is a reference to the object, not a copy of it. So both
chineseBox(the variable) andchineseBox.content(the property) point to the same object, which has a property calledcontent.Let’s throw some ASCII art at this:
That gives us:
+−−−−−−−−−−−−−−−−−−−−−−−+ | chineseBox (variable) | +−−−−−−−−−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−+ | value |−−−−−−−−−>| (object) | +−−−−−−−−−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−+ | | +−−−−−−−−−−−−−−−+Now we do
…and we have:
/−−−−−−−−−−−\ +−−−−−−−−−−−−−−−−−−−−−−−+ | | | chineseBox (variable) | v | +−−−−−−−−−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−+ | | value |−−−−−−−−−>| (object) | | +−−−−−−−−−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−+ | | content |−−−−/ +−−−−−−−−−−−−−−−+There’s just one object. There are two references pointing to it.