DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> document.getElementById介紹
document.getElementById介紹
編輯:關於JavaScript     
把你的大腦當做浏覽器執行下面的代碼兩次,分別是IE6和IE9:
復制代碼 代碼如下:
function testFunc(){
alert('test')
}
$(function(){
var g = document.getElementById ,
w = window.testFunc ;
//g
alert(typeof(g));
alert(String(g));
alert(g instanceof Object);
alert(g instanceof Function);
//w
alert(typeof(w));
alert(String(w));
alert(w instanceof Object);
alert(w instanceof Function);
//執行
alert(g('t'));
w();
});

在標准浏覽器中(IE9、FF、chrome等)上述代碼執行得非常一致,返回結果如下:
typeof => "function"
復制代碼 代碼如下:
String => "function #funcName#{[native code]}"
instanceof Object => true
instanceof Function => true

很奇怪,雖然類型是函數,但是我們卻不能直接使用括號來執行函數g,而需要使用call

g.call(document,elementId);
但是如果運行環境是IE6,一切看起來非常詭異,下面是運行結果(注意粗體部分):
復制代碼 代碼如下:
//g
typeof => "object"
String => "function getElementById{[native code]}"
instanceof Object => false
instanceof Function => false
//w
typeof => "function"
String => "function testFunc{alert('test')}"
instanceof Object => true
instanceof Function => true


在IE 6下,對於g和w都只能使用括號直接執行函數,而不需要使用call。對於函數g使用下面的方式調用會導致一個“對象沒有該屬性”的錯誤:
g.call(document,eleId)
在IE6下,對於自定義的函數testFunc測試結果沒有任何問題,但是對於g卻十分地詭異!

既然g是object那麼為何可以像函數一樣用()直接調用執行?
而在標准浏覽器中,g既然是函數為什麼卻不能直接使用()來執行呢?
事實上對於document.getElementById,它到底是function還是object就連jQuery 1.6.2也沒有解決這個問題。
在IE6中$.isFunction(g)仍然返回的是false!下面是jQuery 1.6.2的jQuery.isFunction的相關源代碼:

復制代碼 代碼如下:
class2type={};
...
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
...
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ Object.prototype.toString.call(obj) ] || "object";
},
...
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
}

於是在StackOverflow上提了這個問題,好在牛人確實多,很快就有了回復。最後我簡單的總結一下給大家參考:
document.getElementById 最初被定義為 HTMLDocument (HTML DOM)接口的一個成員,但是在後來的 2 級 DOM 中移入到 Document (XML DOM)接口中。
document.getElementById屬於host object,它是一個function,但是它並沒有被定義在ECMAScript中而是DOM接口的一部分。
支持[[Call]](內部屬性?)host object的typeof返回值就是function。請記住Host Objects並不總是遵循Native Objects的相關規則,比如typeof。
而對於testFunc它是native object, 更具體地說是native function。
下面是EcmaScript 5對於typeof操作符的返回結果的歸類:

Type of val

Result

Undefined

"undefined"

Null

"object"

Boolean

"boolean"

Number

"number"

String

"string"

Object (native and does not implement [[Call]])

"object"

Object (native or host and does implement [[Call]])

"function"

Object (host and does not implement [[Call]])

Implementation-defined except may not be "undefined", "boolean", "number", or "string".

所以如果要實現用$代替document.getElementById需要這麼做:
復制代碼 代碼如下:
var $ = function(id) { return document.getElementById(g) };

但是即使有了上面的解釋之後,我對Host Object和Native Object又有了新的疑惑。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved