Skip to Content

NCZOnline

Blog Entry

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.

Comments

kangax says:

Yes, good old trick.

Although I prefer to use it explicitly like so:

var global = (function(){ return this; })();

Julien Lecomte says:

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.

Erik Arvidsson says:

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.

Nicholas C. Zakas says:

@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.

Post Comment

Your e-mail address will never be shown, only your URL. Please, no HTML in your comments, as it will be automatically stripped out for security purposes.

(required)
(required, not shown)


Please answer the following silly question to confirm that you are a person and not an evil spam robot:


Copyright © 2004-2005 Nicholas C. Zakas. All Rights Reserved. XHTML | CSS