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 different. It depends on the scope we're accessing it in.
Well, in all projects there is a "global" this
. But it's called something different depending on what context you're in. On the web you may be familiar with it as the window
object. In other contexts it's self
and sometimes it's this
!
As it turns out, there is a function that's been refined over time to always access it.
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');
};
Not exactly pretty. And a pain to include in every project.
But no more! Now at stage 4, globalThis
is the latest addition to ECMAScript.