无法理解JavaScript中的基本对象工作原理

时间:2012-06-26 10:37:55

标签: javascript object

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

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

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

4 个答案:

答案 0 :(得分:3)

  

我认为如果将第二个表达式求值为false,指向前面定义的空chineseBox对象,那就更自然了。

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

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

让我们抛出一些ASCII艺术:

var chineseBox = {};

这给了我们:

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

现在我们做

chineseBox.content = chineseBox;

......我们有:

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

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

答案 1 :(得分:1)

chineseBox.content是对chineseBox的引用;并且重要的是它是一个参考,因为它意味着chineseBox的任何未来更改<{>} 在chineseBox.content参考中都可见。

chineseBox.content设置为chineseBox时,chineseBox对象确实为空;但是因为chineseBox是一个引用,因为在您设置content属性时很快,它会更新以反映出来。

请参阅chineseBox.content === chineseBox // true

答案 2 :(得分:0)

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

答案 3 :(得分:0)

'content' in chineBox.content评估为 true ,因为content指向原始 chineseBox对象(chineseBox.content - &gt; chineseBox )。

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