gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:40:40 26 4
gpt4 key购买 nike

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

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

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

最佳答案

I think it'd be more natural if the second expression evaluated to false, pointing to the empty chineseBox object defined earlier.

它不再是空的。从 chineseBox.content = chineseBox 开始,它现在有一个属性。

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

让我们在此添加一些 ASCII 艺术:

var chineseBox = {};

这给了我们:

+−−−−−−−−−−−−−−−−−−−−−−−+| chineseBox (variable) |+−−−−−−−−−−−−−−−−−−−−−−−+          +−−−−−−−−−−−−−−−+| value                 |−−−−−−−−−>|    (object)   |+−−−−−−−−−−−−−−−−−−−−−−−+          +−−−−−−−−−−−−−−−+                                   |               |                                   +−−−−−−−−−−−−−−−+

Now we do

chineseBox.content = chineseBox;

...我们有:

                                            /−−−−−−−−−−−\+−−−−−−−−−−−−−−−−−−−−−−−+                   |           || chineseBox (variable) |                   v           |+−−−−−−−−−−−−−−−−−−−−−−−+          +−−−−−−−−−−−−−−−+    || value                 |−−−−−−−−−>|    (object)   |    |+−−−−−−−−−−−−−−−−−−−−−−−+          +−−−−−−−−−−−−−−−+    |                                   |  content      |−−−−/                                   +−−−−−−−−−−−−−−−+

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

关于javascript - 难以理解 JavaScript 中的基本对象工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11205518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com