Get the JavaScript global
The global object in JavaScript is vitally important: all global variables and functions become properties fo the global object. In browsers. the window object doubles as the global object, and most developers use it as such without even realizing. In other JavaScript environments, however, the global object is something else. Most of the time, it’s not assigned to a global variable for you to access.
If you code is to run in non-browser JavaScript environments, you’d better avoid using window for dealing with globals. However, referencing the global object can be necessary. To that end, I present the getGlobal() function, which works in any JavaScript environment and always returns the global object:
function getGlobal(){
return (function(){
return this;
}).call(null);
}
The key to this function is that the this object always points to the global object anytime you are using call() or apply() and pass in null as the first argument. Since a null scope is not valid, the interpreter inserts the global object. The function uses an inner function to assure that the scope is always correct. You can then use this function as follows:
var global = getGlobal();
And I suggest you do this whenever writing JavaScript that should be executable in non-browser environments. Enjoy.
Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of my employer, my colleagues, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.
Both comments and pings are currently closed.




4 Comments
Yes, good old trick.
Although I prefer to use it explicitly like so:
var global = (function(){ return this; })();
kangax on April 20th, 2008 at 10:57 pm
If you have full control over the script, you can simply write:
var global = this;
in the global scope. However, Nicholas’ solution works all the time, not matter where the getGlobal function was defined.
Julien Lecomte on April 20th, 2008 at 11:30 pm
function getGlobal() {
return this;
};
or if you want to be safe from bind
function getGlobal() {
return (function() {
return this;
})();
};
In other words, "call" is not needed.
Erik Arvidsson on April 21st, 2008 at 1:07 pm
@Julien – that’s exactly it, I wanted this to work everywhere no matter what.
@Erik – thanks for pointing that out. I got so used to calling functions in another scope with call() that I completely forgot it wasn’t necessary in this case.
Nicholas C. Zakas on April 21st, 2008 at 11:54 pm
Comments are automatically closed after 14 days.