レッスンに戻る

ドキュメントの階層はどこですか?

重要度: 4

documentはどこに属しますか?

DOM階層での位置は?

NodeまたはElementから継承していますか? それともHTMLElementから?

出力することで、どこのクラスに属するかを確認できます。

alert(document); // [object HTMLDocument]

または

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

つまり、documentHTMLDocumentクラスのインスタンスです。

階層での位置は?

仕様を見ることもできますが、手作業で行う方が早いです。

__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からそれらを取得します。