Document、HTMLDocument关系的探究

首先贴上代码: html

1 console.log(Object.getPrototypeOf(document));
2 console.log(Object.getPrototypeOf(Object.getPrototypeOf(document)));

 

在FF上的运行结果以下所示:node

 

 第一行代码返回的是一个HTMLDocument对象,第二行代码返回的是一个Document对象。函数

经过分析咱们能够得出document对象的prototype为HTMLDocument对象,HTMLDocument对象的prototype为Document对象。spa

注意这里的document对象就是咱们常用的document.getElementById()函数中的document,这个document对象让我想到了JavaScript中的Object。prototype

 

《Professional JavaScript for Web Developers》中描述以下:

JavaScript represents document nodes via the Document type. In browsers, the document object is an instance of HTMLDocument (which inherits from Document) and represents the entire HTML page. The document object is a property of window and so is accessible globally.code

 

写这段代码时犯了一些错误:

1. 在全局中声明了一个变量documenthtm

1 var document = new Document();
2 console.log(document.constructor);        // HTMLDocument对象

代码分析:对象

console.log(Object.getOwnPropertyDescriptor(window, "document"));

configurable属性值为false, set函数没有定义,因此咱们根本就不可能改变window.document.blog

上面的代码声明的全局变量document和window.document冲突了,但document的赋值是不会改变window.document的。ip

这里还有一个误区,其实document对象是HTMLDocument()构造函数的一个实例(上面的高程中也有提到),千万不要误觉得document对象是Document()构造函数的实例。

 

2. 实例对象是不能直接经过prototype属性来访问其prototype对象的。

1 console.log(document.prototype);    // undefined

一样,下面这段代码也是错误的:

1 console.log(Object.getPrototypeOf(document).prototype);

 

咱们应该明白prototype chain是经过instance来实现的。所以Object.getPrototypeOf(document)返回的是一个Document()构造函数的instance. instance只有[[Prototype]],这个属性是不能外部使用的。

 

从这个例子中,咱们也能够看出JavaScript(Object),DOM,BOM的联系是多么的紧密~

DOM和BOM的关系能够参考我转的一篇博文[http://www.cnblogs.com/linxd/p/4481052.html]

相关文章
相关标签/搜索