Javascript globalThis

The globalThis property provides a standard way of accessing the global this value (and hence the global object itself) across environments.

if (typeof globalThis.setTimeout !== 'function') {
  // no setTimeout in this environment!
}

Reliably get the global object prior to globalThis.

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

The this keyword could be used inside functions running in non–strict mode, but this will be undefined in Modules and inside functions running in strict mode.

You can also use Function('return this')(), but environments that disable eval(), like CSP in browsers, prevent use of Function in this way.

Instead, we can have codes like below to do the checking:

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') {
  // no setTimeout in this environment!
}

Reference

globalThis - JavaScript | MDN