在IE 8、9和10上,文档是哪个类的实例

On IE 8, 9, and 10, is document an instance of which class?

本文关键字:文档 实例 IE      更新时间:2023-09-26

在Chrome和Firefox的控制台上,我可以进行

Object.getPrototypeOf(document) === HTMLDocument.prototype

得到一个true,意味着documentHTMLDocument类的一个实例。但在IE 8、9或10上,我会得到HTMLDocument is undefined的错误。

那么,在IE 8、9和10上,document是哪个类的实例吗?

(在IE 11预览版上,它是有效的……有点奇怪的是,IE 10如此现代,却没有定义HTMLDocument的标准)。

附带说明:我看到IE上没有遵循模式的奇怪之处:

Object.getPrototypeOf(document)  // => [object DocumentPrototype] { ... }

Object.getPrototypeOf(document) === Document.prototype  // => false

但是

Object.getPrototypeOf(document.body)  // => [object HTMLBodyElementPrototype] { ... }

Object.getPrototypeOf(document.body) === HTMLBodyElement.prototype  // => true

您似乎在问一个永恒的问题,"为什么所有浏览器都不以相同的方式实现主机对象?"。

要回答您关于document的问题,让我们看看document.constructor

Object.getPrototypeOf(document) === document.constructor.prototype; // true

那么,IE中的document.constructor是什么呢?

document.constructor === Document; // true in IE 10, 9
// hence
Object.getPrototypeOf(document) === Document.prototype; // true in IE 10, 9

您会注意到IE8不支持Object.getPrototypeOf或有Document,但它有HTMLDocument

进一步注意,在所有主要浏览器(不包括IE8)中,

document instanceof Document; // true

因此,您可以将Document.prototype用于所有浏览器,尽管我不会真正建议它,因为您可能会破坏其他代码/前向兼容性

Document.prototype.foo = 'bar';
document.foo; // "bar"