The Global Object in Various JavaScript Environments
Each JavaScript environment has its own global object (aka. root object, global namespace object). The global object can be accessed using this operator in the global scope, or by referring to its name directly. In order to write code working for multiple environments, we usually need to detect the global object for use in code.
A List of Global Objects in Various Environments
In Browser Main Threads
-
window: The window property of a window object points to the window object itself. -
self: The Window.self read-only property returns the window itself, as a WindowProxy.
In Browser Worker Threads
-
self: The self read-only property of the WorkerGlobalScope interface returns a reference to the WorkerGlobalScope itself.
In Server Environments (Node.js, io.js)
-
global: The global namespace object. -
GLOBAL,root: Undocumented aliases toglobal.Depreated in Node.js 6.0 by commit 4e46931406. Using them after Node.js 6.0 emits warning to stderr:
DeprecationWarning: 'GLOBAL' is deprecated, use 'global' DeprecationWarning: 'root' is deprecated, use 'global'
Real Life Examples of Detecting the Global Object
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = typeof self === 'object' && self.self === self && self ||
typeof global === 'object' && global.global === global && global ||
this;
-
typeof self === 'object' && self.self === self && selfdetects the global object in browser environments with support for code run inWebWorkerat the same time. -
typeof global === 'object' && global.global === global && globaldetects the global object on the server (e.g. Node.js). -
Using
thisas a fallback to add support for code run in Node.js vm module.
Note that, in fact, using this alone can work in all these environments, but only if the code is not running under strict mode, in which case this in global scope will be undefined.
However, even if you are writing code not in strict mode, as long as you want your code to be able to be imported as a module with ES6 module spec, you should avoid using this alone, as module code is always strict mode code. (See 10.2.1 Strict Mode Code - ECMAScript 2015 Language Specification)
References: underscore Issue #2152, PR #2153, PR #2221.