DEV Community

Discussion on: globalThis is coming to JavaScript

Collapse
 
seanmclem profile image
Seanmclem

What might be a use-case where I would want a globalThis instead of just manually accessing window, or this?

Collapse
 
laurieontech profile image
Laurie • Edited

It's a standard. So it will work consistently regardless of what environment the code is run in.

Collapse
 
mausworks profile image
Rasmus Wennerström

"As consistent as it can get".

Different global objects will expose very different APIs, so now instead of having to check if (typeof global !== 'undefined') global.nodeFeature(), you can now check:

if (globalThis.nodeFeature) { 
  globalThis.nodeFeature();
} else if (globalThis.webFeature) { 
  globalThis.webFeature();
}

I think it's useful, but it's just kind of deferring the problem, as you will still have to write platform-specific abstractions.

Thread Thread
 
seanmclem profile image
Seanmclem

Yeah I guess that was my concern. If the different 'this' you're targeting can have radically different APIs, I would wonder why target them with a single globalThis instead of individually. I figured I was missing something..