【发布时间】:2011-10-30 19:36:17
【问题描述】:
考虑以下代码:
<script>
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);
//run it
alert(g('t'));
w();
});
</script>
代码在现代浏览器(chrome、IE 9、Firefox)中的行为相同。结果是:
typeof => “函数”
String => "函数#funcName#{[本机代码]}"
instanceof 对象 => 真
instanceof 函数 => 真
有点奇怪,我们可以使用()轻松调用w,但是对于g,我们必须像这样调用它:
g.call(document,elementId);
在 IE 6 中,结果完全不同:
//g
typeof => "对象"
String => "函数 getElementById{[本机代码]}"
instanceof 对象 => 假
instanceof 函数 => 假
//w
typeof => "函数"
String => "函数 testFunc{alert('test')}"
instanceof 对象 => 真
instanceof 函数 => 真
更重要的是,我们必须使用'()'直接运行g和w,我们不能这样调用g:
g.call(document,'t')
这将导致错误。
所以这是我的问题:document.getElementById 是什么,函数还是对象,g 和 w 之间的区别是什么?
【问题讨论】:
-
这里的答案是停止支持IE6,让它死掉=D
-
DOM 接口不必表现得像本机 JavaScript 函数/对象。
-
@Tejs:都赞成说:赞成!
-
在 IE7 上也报告了 IE6 行为,
getElementsByTagName
标签: javascript