this, self, window, global, globalThis, etc.
- Planted:
TL;DR: In JavaScript (browser runtimes, at least), this, self, window, frame, and globalThis all point to the same value (the Window object).
Why do they all exist then? Per MDN:
Historically, accessing the global object has required different syntax in different JavaScript environments. On the web you can use
window,self, orframes- but in Web Workers onlyselfwill work. In Node.js none of these work, and you must instead useglobal...The
globalThisproperty provides a standard way of accessing the globalthisvalue (and hence the global object itself) across environments.
I’ve been thinking more about JavaScript runtimes lately. I’d like to confidently know when I can use what (language features and APIs). My takeway here is when in doubt, use globalThis.