返回課程

文件在階層結構中的位置?

重要性:4

document 屬於哪個類別?

它在 DOM 階層結構中的位置?

它繼承自 NodeElement,還是 HTMLElement

我們可以透過輸出它來查看它屬於哪個類別,例如

alert(document); // [object HTMLDocument]

alert(document.constructor.name); // HTMLDocument

所以,documentHTMLDocument 類別的一個實例。

它在階層中的位置是什麼?

是的,我們可以瀏覽規格,但手動找出會更快。

讓我們透過 __proto__ 遍歷原型鏈。

我們知道,類別的方法在建構函式的 prototype 中。例如,HTMLDocument.prototype 有文件的方法。

此外,prototype 內部有一個指向建構函式函式的參考

alert(HTMLDocument.prototype.constructor === HTMLDocument); // true

若要取得類別名稱為字串,我們可以使用 constructor.name。讓我們對整個 document 原型鏈執行此操作,直到類別 Node

alert(HTMLDocument.prototype.constructor.name); // HTMLDocument
alert(HTMLDocument.prototype.__proto__.constructor.name); // Document
alert(HTMLDocument.prototype.__proto__.__proto__.constructor.name); // Node

這就是階層。

我們也可以使用 console.dir(document) 檢查物件,並透過開啟 __proto__ 查看這些名稱。主控台會從 constructor 內部取得它們。