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 onlyself
will work. In Node.js none of these work, and you must instead useglobal
...The
globalThis
property provides a standard way of accessing the globalthis
value (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
.