How to Get the Global Object in JavaScript

How to get the global object in JavaScript?

Well, you can use the typeof operator, and if the identifier doesn't exist in any place of the scope chain, it will not throw a ReferenceError, it will just return "undefined":

if (typeof ModuleName != 'undefined') {
//...
}

Remember also that the this value on Global code, refers to the global object, meaning that if your if statement is on the global context, you can simply check this.ModuleName.

About the (function () { return this; }()); technique, you are right, on strict mode the this value will simply be undefined.

Under strict mode there are two ways to get a reference to the Global object, no matter where you are:

  • Through the Function constructor:

    var global = Function('return this')();

Functions created with the Function constructor don't inherit the strictness of the caller, they are strict only if they start their body with the 'use strict' directive, otherwise they are non-strict.

This method is compatible with any ES3 implementation.

  • Through an indirect eval call, for example:

    "use strict";
    var get = eval;
    var global = get("this");

The above will work because in ES5, indirect calls to eval, use the global environment as both, the variable environment and lexical environment for the eval code.

See details on Entering Eval Code, Step 1.

But be aware that the last solution will not work on ES3 implementations, because an indirect call to eval on ES3 will use the variable and lexical environments of the caller as the environments for the eval code itself.

And at last, you may find useful to detect if strict mode is supported:

var isStrictSupported = (function () { "use strict"; return !this; })();

What is the 'global' object in NodeJS

While in browsers the global scope is the window object, in nodeJS the global scope of a module is the module itself, so when you define a variable in the global scope of your nodeJS module, it will be local to this module.

You can read more about it in the NodeJS documentation where it says:

global

<Object> The global namespace object.

In browsers, the top-level scope is the global scope. That means that
in browsers if you're in the global scope var something will define a
global variable. In Node.js this is different. The top-level scope is
not the global scope; var something inside an Node.js module will be
local to that module.

And in your code when you write:

  • console.log(this) in an empty js file(module) it will print an empty object {} referring to your empty module.
  • console.log(this); inside a self invoking function, this will point to the global nodeJS scope object which contains all NodeJS common properties and methods such as require(), module, exports, console...
  • console.log(this) with strict mode inside a self invoking function it will print undefined as a self invoked function doesn't have a default local scope object in Strict mode.

Getting a reference to the global object in an unknown environment in strict mode

In ES5, you can get a reference to global object from within strict mode via indirect eval call:

"use strict";
var global = (1,eval)('this');

Take a look at my article; particularly at this section on strict mode.

Global object access in strict mode

The reason was already explained by dystroy: this will not be the global object in strict mode. Here is the workaround (assuming that's running on the global scope):

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

The reason, according to the ES5 specification, is:

If this is evaluated within strict mode code, then the this value is not coerced to an object. A this value of null or undefined is not converted to the global object

Define a global variable in a JavaScript function

As the others have said, you can use var at global scope (outside of all functions and modules) to declare a global variable:

<script>
var yourGlobalVariable;
function foo() {
// ...
}
</script>

(Note that that's only true at global scope. If that code were in a module — <script type="module">...</script> — it wouldn't be at global scope, so that wouldn't create a global.)

Alternatively:

In modern environments, you can assign to a property on the object that globalThis refers to (globalThis was added in ES2020):

<script>
function foo() {
globalThis.yourGlobalVariable = ...;
}
</script>

On browsers, you can do the same thing with the global called window:

<script>
function foo() {
window.yourGlobalVariable = ...;
}
</script>

...because in browsers, all global variables global variables declared with var are properties of the window object. (The new let, const, and class statements [added in ES2015] at global scope create globals that aren't properties of the global object; a new concept in ES2015.)

(There's also the horror of implicit globals, but don't do it on purpose and do your best to avoid doing it by accident, perhaps by using ES5's "use strict".)

All that said: I'd avoid global variables if you possibly can (and you almost certainly can). As I mentioned, they end up being properties of window, and window is already plenty crowded enough what with all elements with an id (and many with just a name) being dumped in it (and regardless that upcoming specification, IE dumps just about anything with a name on there).

Instead, in modern environments, use modules:

<script type="module">
let yourVariable = 42;
// ...
</script>

The top level code in a module is at module scope, not global scope, so that creates a variable that all of the code in that module can see, but that isn't global.

In obsolete environments without module support, wrap your code in a scoping function and use variables local to that scoping function, and make your other functions closures within it:

<script>
(function() { // Begin scoping function
var yourGlobalVariable; // Global to your code, invisible outside the scoping function
function foo() {
// ...
}
})(); // End scoping function
</script>


Related Topics



Leave a reply



Submit