ES10 globalThis scope

ES10 released the globalThis property to enable global this context maps to the global object. It provides a unique way of giving access to global objects like windows.

As you know javascript has the support for multiple environments like client, server-side or with IoT or mobiles, Client environment like browser has to use window or self or frames(for web or service workers). These (window, self, or frames) will not work on the server side like the nodejs platform. To handle this, we have to write the custom code to have unique global access for each environment.

 const globalThis=(){
 if (clientside){//return clientGlobalObject}
 if (serverside){//return serverGlobalObject}
  if (mobile){//return mobileGlobalObject}
   if (IOT){//return iotGlobalObject}
}

It will not work when a new environment comes as you have to again write separate conditions to handle this. To make it unique of accessing global objects in multiple environments,globalThis is introduced to get global context on any environment.

Alternatives to globalThis in Browser:

In a client-side application like browsers, windows and frames are global objects so globalThis is the same as window and frames=globalThis selfs is equal to globalThis in web or services workers as window and frames are undefined in this.

Alternative in Nodejs There is no window or self or frames in the nodejs environment. global is available and equal to globalthis.

Syntax:

globalThis.[variable]= data

An example for accessing global this scope data:

function setGlobalData() {
    globalThis.mydata ='testthis';
}
setGlobalData();
console.log(globalThis.mydata ); //outputs testthis

we can save data to global this scope like object assignment, retrieve this with globalThis with accessor.

polyfill to support all platforms

This is ES10 features, To support older browsers, the following is the code to handle fallback cases.

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;
  if (typeof this !== 'undefined') return this;
  throw new Error('Could not find global this `this`');
};
var globalThisScopeObject = getGlobalThis();

Babel Syntax support.

@babel/preset-env is the plugin used to use the latest features without worrying about the latest changes Configure babel plugin in nodejs projects using npm or yarn

npm install --save-dev @babel/preset-env
yarn add @babel/preset-env --dev

.babelrc

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "usage"
      }
    ]
  ]
}

Supported versions

This feature is supported in the following JavaScript engines and browsers as per V8

  • V8 6.6
  • Node12+
  • Chrome 71+
  • Firefox 65+
  • Opera 53+
  • Safari 12.1+