globalThis is coming to JavaScript

Laurie on November 21, 2019

One of the first things we learn with JavaScript is the keyword this. What is tricky to understand at first is that its definition is always differ... [Read Full]
markdown guide

Nobody will ever be happy with the name globalThis 😂

Seems really useful though!


Yeaaa... usefulness is an 11/10 but name scheme is about a -1/10


I don't see why they couldn't just name it global. There's the "let's not conflict"-argument, and "let's fight around with existing types".

But in all honesty... there's not much you can "assume" about the global object anyways, you will still have to check if (global.feature) for most features if you're building a cross-platform lib, and I'm not sure how globalThis would help with that.


"Attempts were made to ship under the name global, but it turns out that this does, in fact, break some existing websites." per the spec github.com/tc39/proposal-global


Ugh I wish I had that func you just offered up my sleeve


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


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


"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) { 
} else if (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.

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..

code of conduct - report abuse