Is JavaScript’s “Global” Scope Really Just A Closure?
I hear a lot of talk about how it’s a performance penalty to use globally scoped variables in JavaScript (not to mention, dangerous / dumb). When a function looks for a variable, it checks the current scope, then it checks any outer scopes that the function may be nested in, and finally it reaches the outer-most scope: the global scope of the JavaScript runtime.
It occurred to me, as I was wrapping up the edits for my “Variable Scope In JavaScript” screencast, that this is evidence to suggest that access to the global scope, from anywhere other than the global scope in a JavaScript runtime environment, is nothing more than a closure.
Look at it this way: when we access the “foo” variable from within the “sayFoo” function of this code
(click the link for the JSFiddle, if you’re in an RSS reader) the runtime has to step out of the “sayFoo” function and find the “foo” variable declared in the “outerScope” function.
Now look at similar code accessing the `$` variable from jQuery, as well as a `bar` variable defined in the outermost, global scope:
Honestly, I had always assumed that there was something special about the global scope of a JavaScript runtime. I had assumed that the browsers and other runtimes had to build some special mechanism in which the global scope was made available to other scopes. It looks like global scope is nothing more than the bi-product of the closure support that JavaScript has built into it, in combination with the outermost scope of the runtime (a DOMWindow or some other scope for CommonJS implementations).
… mystery, suddenly not so mysterious.