Finding JavaScript’s Global Object

With JavaScript code being written in ever more diverse environments these days, some assumptions are bound to get broken. One such assumption is that the object bound to the symbol window in the current scope is the global object. Every approach I’ve seen searches through a list of probable symbols and returns the first defined, instead of using the language itself.

var global = (typeof window != 'undefined' ? window : global)

Below is a snippet that will return the global object independent of scope and interpreter.

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

Note: except in the rarest of cases, direct address of the global object is illegitimate regardless of approach, using this more robust snippet is no excuse.

Leave a Reply