Document、HTMLDocument關系的探究


首先貼上代碼: 

1 console.log(Object.getPrototypeOf(document));
2 console.log(Object.getPrototypeOf(Object.getPrototypeOf(document)));

 

在FF上的運行結果如下所示:

 

 第一行代碼返回的是一個HTMLDocument對象,第二行代碼返回的是一個Document對象。

通過分析我們可以得出document對象的prototype為HTMLDocument對象,HTMLDocument對象的prototype為Document對象。

注意這里的document對象就是我們經常使用的document.getElementById()函數中的document,這個document對象讓我想到了JavaScript中的Object。

 

《Professional JavaScript for Web Developers》中描述如下:

JavaScript represents document nodes via the Document type. In browsers, the document object is an instance of HTMLDocument (which inherits from Document) and represents the entire HTML page. The document object is a property of window and so is accessible globally.

 

寫這段代碼時犯了一些錯誤:

1. 在全局中聲明了一個變量document

1 var document = new Document();
2 console.log(document.constructor);        // HTMLDocument對象

代碼分析:

console.log(Object.getOwnPropertyDescriptor(window, "document"));

configurable屬性值為false, set函數沒有定義,所以我們根本就不可能改變window.document.

上面的代碼聲明的全局變量document和window.document沖突了,但document的賦值是不會改變window.document的。

這里還有一個誤區,其實document對象是HTMLDocument()構造函數的一個實例(上面的高程中也有提到),千萬不要誤以為document對象是Document()構造函數的實例。

 

2. 實例對象是不能直接通過prototype屬性來訪問其prototype對象的。

1 console.log(document.prototype);    // undefined

同樣,下面這段代碼也是錯誤的:

1 console.log(Object.getPrototypeOf(document).prototype);

 

我們應該明白prototype chain是通過instance來實現的。因此Object.getPrototypeOf(document)返回的是一個Document()構造函數的instance. instance只有[[Prototype]],這個屬性是不能外部使用的。

 

從這個例子中,我們也可以看出JavaScript(Object),DOM,BOM的聯系是多么的緊密~

DOM和BOM的關系可以參考我轉的一篇博文[http://www.cnblogs.com/linxd/p/4481052.html]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM