Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is document.getElementById?

Tags:

javascript

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?

like image 534
simon xu Avatar asked Aug 19 '11 17:08

simon xu


1 Answers

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.

like image 69
Mike Samuel Avatar answered Oct 15 '22 04:10

Mike Samuel