DEV Community

Cover image for 🛑Stop using `this` instead use `globalThis` for global variables
Michael "lampe" Lazarski
Michael "lampe" Lazarski

Posted on

🛑Stop using `this` instead use `globalThis` for global variables

We all know that this in Javascript is a topic where people struggle with. If we now not only think about plain javascript but look in what environment we are running our Javascript code it gets even more complicated.

So you as a developer need to understand what the current global object is?

It is a different object depending on the execution environment you run your code.

What are the usual environments your Javascript code is running in?

A Browser like Firefox, Chrome, Edge, or Opera. The global object here is the window. Writing window.setTimeout() and setTimeout is in a Browser the same. This does not work everywhere. You also have the frames object but most of the time this frames object is equal to the window object.

NodeJS does not know window. In node you have to use global to for example add a function globally. Another diffrences is that nodejs variables are scoped to the module not the the global object. Something like var a = 10 and then checking for it beeing to equal to the global variable will return false. To make it more clear hear is an example:

// Browser Enviourment
var a = 10;
a === window.a // true
// NodeJS Enviourment
var a = 10;
a === global.a // false

Since Deno is built in mind of web standards. It has access to the window object.

Then you have WebWorkers where you have self and you can not access this or window and so on.

I think the problem now should be pretty clear.
Writing universal Javascript is kind of hard.

We can of course polyfill it like that:

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(); 

The problem is you have to remember to use the globals variable and you need to import or set it up somehow globally for you.

This is why globalThis was introduced into Javascript.

You can use it right now it is supported by all major Browsers besides IE11. But should we really care about a 7-year-old browser? It depends on your project needs.

So how can you use the globalThis. It is actually very easy:

// Browser
console.log(globalThis) // returns the window object
// NodeJS
console.log(globalThis) // returns the globals object
// WebWorkers
console.log(globalThis) // returns the global web workers context

Easy right? so now you don't need to worry about this anymore and can code away.

One thing is still the same es before. Functions like alert() which are exclusive to the Browser will still not work.

Resources

👋Say Hello! Instagram | Twitter | LinkedIn | Medium | Twitch |

Top comments (14)

Collapse
 
moopet profile image
Ben Sinclair

They've chosen a poor name there, I think. 'global' implies it's the top level, this implies it's local to whatever context you're in. Everyone should be able to access "global" scope, but other modules shouldn't see your this.

So how is globalThis a name that's going to work? It's another way Javascript is getting more confusing. Wouldn't it be better to suggest not sharing global scope at all?

Collapse
 
lampewebdev profile image
Michael "lampe" Lazarski

You can read more about it here: github.com/tc39/proposal-global/is...

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

I thought globalThis has more to do with context of environment. The title of this post is a bit misleading in a way.. kind of, this bleeding out to a global scope is an unfortunate accident in my book rather than explicit intention using window or module or global etc. Maybe stop using this to target the global scope.

Collapse
 
lampewebdev profile image
Michael "lampe" Lazarski

Hmm this is why I added the "for global variables".

I thought this would be enough?

What would be a better title?

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀 • Edited

'Stop using global variables and if you have to, think about if your code is isomorphic, then if it is use globalThis'. It's a bit wordy. Sorry I think your title is better.

Thread Thread
 
lampewebdev profile image
Michael "lampe" Lazarski

haha, that's the problem with title :D
Coming up with a good title is an art.
And I'm bad at it :D

Collapse
 
huncyrus profile image
huncyrus

Quite interesting and good to know, could help quick prototyping, especially if accessible from multiple files.
But then some question, what I did not found at the first search:

  • execution order? (can it lock, overwrite, how consistent it could be?)
  • can a forked process also reach the same or every started process shall have its own 'global this'?

I'm curious what people opinion is, especially if we thing on other languages - somewhat - strict general practice what basically start with: 'Do not use global, nor enabled them'.

Collapse
 
rajdeepc profile image
Rajdeep Chandra

I think they have introduced a new standard 'globalThis' to be a cross node solution in ES2020

Collapse
 
lampewebdev profile image
Michael "lampe" Lazarski

yes :D
That's what I was trying to say in this post.

Collapse
 
rajdeepc profile image
Rajdeep Chandra

Yea but since a lot of frameworks and libraries are encouraging us to move to functional paradigm we might not use it in future.Nonetheless it is still a good concept to keep in mind.

Thread Thread
 
lampewebdev profile image
Michael "lampe" Lazarski

Yeah but internal stuff in the frameworks and in specific cases you will need to use it :)

Collapse
 
entrptaher profile image
Md Abu Taher

Interesting, didn't know about this. Does it come with any side effects?

Collapse
 
lampewebdev profile image
Michael "lampe" Lazarski

Not that I know right now.

Collapse
 
helloitsm3 profile image
Sean

If you have global variables, why would you still be using this? It makes no sense