2012-06-26 24 views
1

我正在學習JavaScript,並且在我使用的書中有一個示例,我不明白。 是這樣的:理解JavaScript中的基本對象工作時遇到的問題

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

然後書中列舉兩個表達式,它們的值。首先,"content' in chineseBox;返回true。然後,我沒有得到的那個,"content" in chineseBox.content其中也返回true。 我認爲如果第二個表達式的計算結果爲false,則指向前面定義的空對象chineseBox會更自然。 有沒有理由這樣工作?這個功能的實際含義是什麼? 如何探索對象的更深層次?是chineseBox.content.content對不對?

+0

在JavaScript中有什麼{c​​ontent:\ [Circular \]}是什麼意思?](http://stackoverflow.com/questions/7923959/what-does-content-circular-mean-in-javascript) – Esailija

+1

@Esailija:不會說這是一個騙局。這是相同的代碼,但措辭不同。 – Matt

+0

@Matt回答這個問題意味着你必須回答這個問題......即使他們的措詞不同。看到答案。 – Esailija

回答

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  |----/ 
            +---------------+

只有一個對象。有兩個參考文獻指向它。

+0

+1藝術不僅僅是爲了藝術! – RobG

+1

圖紙真的幫了我。謝謝! – BeetleTheNeato

1

chineseBox.contentchineseBox的引用;因此它意味着對chineseBox的任何未來更改均​​爲也參考中可見是重要的。

當您將chineseBox.content設置爲chineseBox時,chineseBox對象確實爲空;但是因爲chineseBox是參考,因爲很快當您設置content屬性時,它會更新以反映該情況。

chineseBox.content === chineseBox // true

0

chineseBox.content = chineseBox;意味着chinesesBox.content點回chineseBox。所以,是的,你可以去chineseBox.content.content.content等,因爲每次你要回根元素

0

'content' in chineBox.content評估爲真正因爲content指向chineseBox對象(chineseBox.content - > chineseBox) 。

chineseBox.content.contentchineseBox.content.content....content都是有效的,因爲你是指同一個對象。

+0

@MarcelKorpel:**原始**意義上的原始。 – user278064

相關問題