ES10 - globalThis

This tutorial covers globalThis access to global Object in uniform way introduced ES2019 with examples..

ES10 globalThis scope

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

As you know java script 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 server side like nodejs platform. To handle this, we have to write the custom code to have unique a global access for each environment.

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

This will not work when new environment comes as you have to again write separate if condition to handle this. To make unique of accessing global object in multiple environments,globalThis is introduced to get global context on any environment.

Alternatives to globalThis in Browser

In a client side applications like browsers, window and frames are global objects so globalThis is same as window and frames=globalThis selfs is equal as 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 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 in older browsers, Following is the code to handle fall back 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 latest features without worrying about 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 supported in the following JavaScript engines and browsers as per V8

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