Standard specifications
HTML5 specification document points out: If an element meets either of the following two rules, then the window object must have a corresponding attribute, and the attribute value is this object .
Let's look at an example. Suppose there is a page that contains a div element with the ID attribute "foo":
> foo
[object HTMLDivElement]
//The error console output the following warning.//Element referenced by ID/NAME in the global scope.
//Use W3C standard document. getElementById() instead.> "foo" in window true
What is going on? When initialized, window does not have the attribute foo. But when this attribute is accessed for the first time (either directly through the window.foo attribute or through the global variable foo), it will be automatically created.
Translator's Note: I did not find warnings in Firefox14, 15, and 18, but there was indeed a warning when testing Firefox12.
[Note: The code in the example can only be effective when run through the script tag in the web page and cannot be run through the terminal. This is because the terminal uses different methods when handling global objects.]
Translator’s Note: I tried the code in the example in Firebug and didn’t find any difference.
Once you try to read the value of foo, although the div element will be returned normally, there will be a warning in the error console telling you that you should not do that. Obviously, such a warning is correct : You can use this feature when debugging in the terminal, but in actual code, you should not use it.
Cody Lindley wrote a jsPerf test to compare accessing foo via global variables with accessing foowindow.foo. Interestingly, only accessing window.foo in Firefox is faster.