What is globalThis in JavaScript

What is globalThis in JavaScript

·

2 min read

The javascript languages are increasingly used in a wide variety of environments. In addition to the web browsers which is the most common type of host environment for JavaScript programs in server, smartphones, and even robotic hardware.

Each environment has its object model and provides a different syntax to access the global objects. In the web browser, for example, the global object is accessible via window, self, or frames. In NodeJS, however, these properties don't exist, and you must use global instead. In web workers, only self is available.

These different ways of referencing the global object have made it tough to write a portable JavaScript code that works in multiple environments. Fortunately, there's a person in the works that aim to fix this issue by introducing a standard property called globalThis that will be available in all environments.

// browser environment
console.log(globalThis); // window

// node.js environment
console.log(globalThis); // Object[global]{...}

// web worker environment
console.log(globalThis); // DedicatedWorkerGlobalScope {...}

Creating a globalThis polyfill

(function() {
    if (typeof globalThis === 'object') return; 
    Object.defineProperty(Object.prototype, '_magic_', {
        get: function () {
            return this; 
        }, 
        configurable: true // this makes it possible to `delete` the getter later
    }); 
    _magic_.globalThis = _magic_; 
    delete Object.prototype._magic_; 
}()); 

// your code can use `globalThis` now
console.log(globalThis);

Mathias Bynens at Chrom Devtools created this polyfill, it is a more robust solution compared to other approaches, but it's still not perfect. Modifying Object, Object.defineProperty could break the polyfill.

Thanks for Reading

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!