consider the following code:
<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>
the code behaves the same in modern browser(chrome,IE 9,Firefox).And the result is:
typeof => “function”
String => “function #funcName#{[native code]}”
instanceof Object => true
instanceof Function => true
it is a little weird, we can easily invoke w by using (), but for g, we must invoke it like this:
g.call(document,elementId);
When it comes to IE 6, the result is totally diffrent:
//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
what is more,we must run g and w directly by using ‘()’, and we can not invoke g like this:
g.call(document,'t')
this will cause an error.
So here is my question: what is document.getElementById, function or object, and what is the diffrence between g and w?
document.getElementByIdis a host object and it is a function. It is not defined in EcmaScript but is part of the DOM interface.Since it supports the
[[Call]]operator it is also a function.Host objects do not always obey the same rules as native objects w.r.t.
typeofthough section 11.4.3 of EcmaScript 5 has tightened the rules somewhat.testFuncis a native object, specifically a native function.