难以理解JavaScript中的基本对象工作

Trouble understanding basic object workings in JavaScript

本文关键字:对象 工作 JavaScript      更新时间:2023-09-26

我正在学习JavaScript,我正在使用的书中有一个我不明白的例子。是这样的:

var chineseBox = {};
chineseBox.content = chineseBox;

然后,本书列出了两个表达式及其值。首先,"content' in chineseBox;返回true .然后,我没有得到的那个,"content" in chineseBox.content它也返回true.我认为如果第二个表达式的计算结果为 false ,指向前面定义的空chineseBox对象会更自然。有理由这样工作吗?此功能的实际含义是什么?如何探索对象的更深层次?chineseBox.content.content对吗?

我认为如果第二个表达式的计算结果为 false ,指向之前定义的空chineseBox对象,那会更自然。

它不再是空的了。截至chineseBox.content = chineseBox,它现在有一个属性。

将对象引用分配给事物(变量、属性等)时,存储的值是对对象的引用,而不是对象的副本。因此,chineseBox(变量)和chineseBox.content(属性)都指向同一个对象,该对象具有一个名为 content 的属性。

让我们在这里抛出一些ASCII艺术:

var chineseBox = {};

这给了我们:

+−−−−−−−−−−−−−−−−−−−−−−−+|中文盒 (可变) |+−−−−−−−−−−−−−−−−−−−−−−−+          +−−−−−−−−−−−−−−−+|值 |−−−−−−−−−−−−−−>|   (对象) |+−−−−−−−−−−−−−−−−−−−−−−−+          +−−−−−−−−−−−−−−−+                                   |              |                                   +−−−−−−−−−−−−−−−+

现在我们做到了

chineseBox.content = chineseBox;

。我们有:

                                            /−−−−−−−−−−−''+−−−−−−−−−−−−−−−−−−−−−−−+                   |          ||中文盒 (可变) |                  V |+−−−−−−−−−−−−−−−−−−−−−−−+          +−−−−−−−−−−−−−−−+    ||值 |−−−−−−−−−−−−−−>|   (对象) |   |+−−−−−−−−−−−−−−−−−−−−−−−+          +−−−−−−−−−−−−−−−+    |                                   | 内容 |−−−−−/                                  +−−−−−−−−−−−−−−−+

只有一个对象。有两个引用指向它。

chineseBox.content是对chineseBox的引用;重要的是它是一个引用,因为这意味着将来对chineseBox的任何更改可见于chineseBox.content引用中。

当您将chineseBox.content设置为 chineseBox 时,chineseBox 对象确实为空;但是chineseBox是一个引用,一旦您设置 content 属性,它就会更新以反映这一点。

chineseBox.content === chineseBox // true

chineseBox.content = chineseBox;表示chinesesBox.content点回到chineseBox。所以是的,你可以去chineseBox.content.content.content等,因为每次你都要回到根元素

'content' in chineBox.content的计算结果为true,因为content指向原始chineseBox对象(chineseBox.content --> chineseBox)。

chineseBox.content.contentchineseBox.content.content....content都是有效的,因为您引用的是同一个对象。