3 ms·
> TL;DR globalThis is not “the global object”; it’s simply the this from the global scope. Thanks to Domenic for helping me understand this important nuance. C
by josteink 7y ago
> TL;DR globalThis is not “the global object”; it’s simply the this from the global scope. Thanks to Domenic for helping me understand this important nuance.
Can someone in the JavaScript community please enlighten me and tell me why you would want to be able to obtain a reference to “globalThis” rather than just the global object itself?
Maybe I’m just being presumptuous, but I suspect that’s what this object is going to be used for anyway, for storing global state. And then it might as well just be called global, right?
Unless of course you want to permeate the chaos that is JS “this” into this new global context, but who would deliberately want to do that?
- deleted 7y ago[deleted]
- bzbarsky 7y agoA few things: 1) In browsers, the actual global (the Window) is _never_ exposed to script. The reasons for that used to do with same-origin policy enforcement, with exposure of the Window to script being considered a security bug in various browsers for a while, but I'm not sure those reasons are still relevant nowadays. At this point, the main reason the WindowProxy is what's exposed is that this is what web authors and web code expect. It's actually quite terrible, because it conflates two objects: "the web page" (corresponding to the non-exposed Window) and "the thing we load web pages in" (corresponding to the WindowProxy). _That_ is a design mistake in the web's object model that dates back to the mid-'90s... In any case, the upshot is that in browser window contexts you can't get a reference to the global; the only thing you can get is the thing that is globalThis. In other contexts (web workers, Node), the two are the same thing. 2) The property naming is ... well, read https://github.com/tc39/proposal-global/blob/master/NAMING.md https://github.com/tc39/proposal-global/blob/master/NAMING.m... for a (longish) summary. Node uses "global", but browsers couldn't do that because it broke some websites. Browsers use "self", but Node wasn't willing to do that, citing concern over the same sort of breakage. And so on, and so forth.