FrontendDeveloper.in

ECMAScript question detail

globalThis

Prior to ES2020, you need to write different syntax in different JavaScript environments(cross-platforms) just to access the global object. It is really a hard time for developers because you need to use window, self, or frames on the browser side, global on the nodejs, self on the web workers side.

On the other hand, this keyword can be used inside functions for non-strict mode but it gives undefined in strict mode. If you think about Function('return this')() as a solution for above environments, it will fail for CSP enabled environments(where eval() is disabled).

In the older versions, you can use es6-shim as below,

var getGlobal = function () {
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
};

var globals = getGlobal();

if (typeof globals.setTimeout !== 'function') {
console.log('no setTimeout in this environment or runtime');
}

In ES2020, globalThis property is introduced to provide a standard way of accessing the global this value across environments.

if (typeof globalThis.setTimeout !== 'function') {
console.log('no setTimeout in this environment or runtime');
}
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399