1

我正在学习 JavaScript,我正在使用的书中有一个我不理解的示例。就像这样:

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

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

4

4 回答 4

3

我认为如果第二个表达式评估为false指向chineseBox前面定义的空对象会更自然。

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

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

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

var chineseBox = {};

这给了我们:

+−−−−−−−−−−−−−−−−−−−−−−−−−−+
| chineseBox (变量) |
+−−−−−−−−−−−−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−−+
| 值 |−−−−−−−−−−>| (对象) |
+−−−−−−−−−−−−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−−+
                                   | |
                                   +−−−−−−−−−−−−−−−−−+

现在我们做

chineseBox.content = chineseBox;

...我们有:

                                            /−−−−−−−−−−−−\
+−−−−−−−−−−−−−−−−−−−−−−−−−+ | |
| chineseBox (变量) | v |
+−−−−−−−−−−−−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−−+ |
| 值 |−−−−−−−−−−>| (对象) | |
+−−−−−−−−−−−−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−−+ |
                                   | 内容 |−−−−/
                                   +−−−−−−−−−−−−−−−−−+

只有一个对象。有两个参考文献指向它。

于 2012-06-26T10:42:27.433 回答
1

chineseBox.content是对chineseBox;的引用 重要的是它是一个参考,因为这意味着任何未来的更改chineseBox可以chineseBox.content参考中看到。

当你设置chineseBox.contentchineseBox时,chineseBox对象确实是空的;但是,因为chineseBox是参考,所以一旦您设置了content属性,它就会更新以反映这一点。

chineseBox.content === chineseBox // true

于 2012-06-26T10:41:28.837 回答
0

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

于 2012-06-26T10:41:56.253 回答
0

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

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

于 2012-06-26T10:42:23.347 回答