🏷️globalThis

JSscopeglobalobject ⟩ globalThis

(⭐️ ES2020)

identifier for the global object, regardless of the current context and environment.

// define a cross-environment polyfill that's safer 
// across pre-globalThis JS environments
const theGlobalObject =
    
    (typeof globalThis !== "undefined") ? globalThis :    // ES2020
    (typeof global     !== "undefined") ? global     :    // Node.js
    (typeof window     !== "undefined") ? window     :    // browser
    (typeof self       !== "undefined") ? self       :    // web worker

    // • such a function will automatically be run in "non-strict mode" 
    //   when invoked with the normal () function invocation.
    // • its `this` will point at the "global object".
    (new Function("return this"))();                      // other environments?

Last updated