What is globalThis in Javascript? What will be the ideal use case for this?
Asked Answered
P

2

34

Recently I have come across about globalThis in Javascript. I am not sure how it is going to behave if it is called from a function. Every time it is returning the window object. if that is the case, then why don't we directly use the window object. What is necessary of using globalThis?

If I call the from a function, then it is returning window object Example:

(function test(){
    console.log(globalThis); // returns window
})();


var obj = {
    key1: function(){
        console.log(globalThis)
    },
    key2: ()=>{
        console.log(globalThis)
    },
    key3: function(){
        var arrFn = () => {
            console.log(globalThis);
        }
        arrFn();
    }
};

obj.key1(); // returns window object
obj.key2(); // returns window object
obj.key3(); // returns window object

I believe the internal implementation of globalThis is like the below code:

const getGlobalThis = () => {
  if (typeof globalThis !== 'undefined') return globalThis;
  if (typeof self !== 'undefined') return self;
  if (typeof window !== 'undefined') return window;
  if (typeof global !== 'undefined') return global;
  // Note: this might still return the wrong result!
  if (typeof this !== 'undefined') return this;
  throw new Error('Unable to locate global `this`');
};
const theGlobalThis = getGlobalThis();

Can anyone please explain to me the exact use case of the globalThis? What will be the ideal scenario to use this?

Popover answered 23/7, 2019 at 6:26 Comment(4)
The support of globalThis is there in every browser.Popover
@VLAZ developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Galleywest
Saswat: What is missing from this 👆 description that is unclear…?Galleywest
@Galleywest I guess I learn something new every day...Futrell
M
42

As MDN says:

The global globalThis property contains the global this value, which is akin to the global object.

Why it's useful:

Historically, accessing the global object has required different syntax in different JavaScript environments. On the web you can use window, self, or frames - but in Web Workers only self will work. In Node.js none of these work, and you must instead use global.

The globalThis property provides a standard way of accessing the global 'this' value (and hence the global object itself) across environments. Unlike similar properties such as window and self, it's guaranteed to work in window and non-window contexts. In this way, you can access the global object in a consistent manner without having to know which environment the code is being run in. To help you remember the name, just remember that in global scope the this value is globalThis.

If you don't know for certain what environment the code is going to be run in, or don't feel like keeping track of it (less cognitive overhead is a good thing, after all!), you can use globalThis instead.

If you know for sure what environment your code is going to be running in, and that the code will never be ported to a different environment, feel free to just keep using window (or the appropriate other property for the environment's global object).

Martynne answered 23/7, 2019 at 6:30 Comment(0)
B
0

Before globalThis, different JavaScript environments had their own global objects, leading to inconsistencies:

In Browsers: window is the global object in most browsers. self and frames also refer to the global object but are less commonly used. For example:

// In a browser

console.log(window); //Logs the global object
console.log(self);  // Logs the same global object as window

In Node.js: The global object is global. For example:

//In Node.js
console.log(global); // Logs the global object

To address this inconsistency, ECMAScript introduced globalThis in ECMAScript 2020. It provides a unified way to access the global object across all environments:

In Browsers:

// In any browser
console.log(globalThis); // Logs the same global object as window

In Node.js:

// In Node.js
console.log(globalThis); // Logs the same global object as global
console.log(globalThis===global); True

Using globalThis ensures that your code interacts with the global object consistently, regardless of the environment. This simplifies cross-platform development and eliminates the need to handle different global objects for different environments.

Bast answered 22/8 at 19:36 Comment(1)
I don't know if this answer adds much more than the one @Martynne gave 5 years agoHalting

© 2022 - 2024 — McMap. All rights reserved.