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>
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.getElementById
is a host object and it is a function. It is not defined in EcmaScript but is part of the DOM interface.
4.3.8 host object
object supplied by the host environment to complete the execution environment of ECMAScript
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. typeof
though section 11.4.3 of EcmaScript 5 has tightened the rules somewhat.
testFunc
is a native object, specifically a native function.
4.3.6 native object
object in an ECMAScript implementation whose semantics are fully defined by this specification rather than by the host environment.
NOTE Standard native objects are defined in this specification. Some native objects are built-in; others may be constructed during the course of execution of an ECMAScript program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With