Is 'window' Always On Top Of The Scope Chain In Javascript?
Solution 1:
The last object on the scope chain in any ECMAScript environment is always the global object. In browsers, window
is to all intents and purposes the global object. If you want to access a property of the global object x
or a global variable x
(which are almost but not quite the same thing), you should explicitly qualify it with window.x
to avoid the possibility of x
being resolved as a property of another object on the scope chain, or globalObj.x
if you care about portability to non-browser environments. You can get a reference to the global object from anywhere in ECMAScript 3 or non-strict ECMAScript 5 as follows:
var globalObj = (function() { returnthis; })();
Solution 2:
window.x
is safer than simply x
if there might possibly be another x
in the current or preceding scopes. That being said, even window
isn't fool-proof because you could define a variable named window
.
Solution 3:
They have similar effects, but window
lets you explicitly declare that you're deliberately using a global. Otherwise, the reader doesn't know whether it's a var
further up the scope chain, you just forgot to declare it, etc.
Solution 4:
Unless you introduce another scope, e.g. by wrapping your code in a function, window === this === <the global scope>
However, window
and this
have the advantage that you can use the array syntax (window['something']
) so you can access globals even if you have their name only in a string without using evil things like eval
.
Solution 5:
The answer is yes. If you declare a variable without the var
keyword (inside a function), the variable will become implicitely a member of the window
object, that is automatically initialized by the browser.
Outside a function, with or without the var
keyword, the variable becomes implicitely a member of the window
object.
Post a Comment for "Is 'window' Always On Top Of The Scope Chain In Javascript?"