在层级结构中,“document”在哪里?
重要性: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。让我们对整个 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 获取这些名称。