3 ms·
I'm surprised to find that this trick still works even in the new backwards-incompatible JavaScript Modules (using <script type="module">), which enables "stric
by dfabulich 4y ago
I'm surprised to find that this trick still works even in the new backwards-incompatible JavaScript Modules (using <script type="module">), which enables "strict" mode and a number of other strictness improvements by default.
I believe it works because the global object ("globalThis") is the Window in either case; this is why JavaScript Modules can refer to "window" in the global scope without explicitly importing it.
<!DOCTYPE html><body>
<div id="cool">cool</div>
<script>
console.log(this); // Window
console.log(globalThis); // Window
console.log("script", cool.innerHTML); // script cool
</script>
<script type="module">
console.log(this); // undefined
console.log(globalThis); // Window
console.log("module", cool.innerHTML); // module cool
</script>
</body></html>
This seems like a missed opportunity. JavaScript Modules should have been required to "import {window} from 'dom'" or something, clearing out its global namespace.
- eyelidlessness 4y agoThere is some effort to standardize something along these lines. Well, some things which combined would achieve this. It’s too late to bake it into ESM, but I believe it’ll be possible with ShadowRealms[1] and/or SES[2], and Built-in Modules (JS STL)[3]. 1: https://github.com/tc39/proposal-shadowrealm https://github.com/tc39/proposal-shadowrealm 2: https://github.com/tc39/proposal-ses https://github.com/tc39/proposal-ses 3: https://github.com/tc39/proposal-built-in-modules https://github.com/tc39/proposal-built-in-modules
- dullcrisp 4y agoLuckily the Reddit thread has the Yu-Gi-Oh! jokes so I don't have to repeat them here.
- eyelidlessness 4y agoI don’t know what jokes or Reddit thread you’re referring to or why it has anything to do with my comment referencing three technical proposals, but I’ll take your word for it that you don’t have to repeat them here.
- dullcrisp 4y agohttps://www.reddit.com/r/javascript/comments/t8mdli/future_javascript_shadowrealms/ https://www.reddit.com/r/javascript/comments/t8mdli/future_j... if you’re curious. Didn’t mean to be overly vague, I just think ShadowRealms is an unusually funny name for a technical proposal. I guess it doesn’t have the same effect if you didn’t grow up watching the same cartoons.