ドキュメントの階層はどこですか?
重要度: 4
document
はどこに属しますか?
DOM階層での位置は?
Node
またはElement
から継承していますか? それともHTMLElement
から?
出力することで、どこのクラスに属するかを確認できます。
alert(document); // [object HTMLDocument]
または
alert(document.constructor.name); // HTMLDocument
つまり、document
はHTMLDocument
クラスのインスタンスです。
階層での位置は?
仕様を見ることもできますが、手作業で行う方が早いです。
__proto__
を使用してプロトタイプチェーンをたどってみましょう。
ご存知のとおり、クラスのメソッドはコンストラクタのprototype
にあります。たとえば、HTMLDocument.prototype
にはドキュメントのメソッドがあります。
また、prototype
内部にはコンストラクタ関数の参照があります。
alert(HTMLDocument.prototype.constructor === HTMLDocument); // true
クラスの名前を文字列として取得するには、constructor.name
を使用できます。 クラスNode
まで、document
プロトタイプチェーン全体で行ってみましょう
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
からそれらを取得します。