测试代码
<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"/><title>全局引用globalThis</title>
<style>
table {border-collapse:collapse; table-layout:fixed; width:33%; border:1px solid #999aaa;}
td{border:1px solid #cccccc; }
tbody>:nth-child(odd){background-color:#aaccff;}
</style><script>function dgebi(x){if(x && x.constructor===String)x=document.getElementById(x); return x;} ; function dcept(p,tn){var e=document.createElement(tn); p=dgebi(p); p.appendChild(e); return e;}
</script></head><body><header id="BodyHeader">
<h1>globalThis</h1>
<blockquote style="color:#999aaa; font-size:16px;">全局属性 globalThis 包含全局的 this 值,类似于全局对象(global object)。<blockquote>
</header><div id="BodyDiv010">
<table>
<thead>
<tr><th>表达式</th> <th>结果</th></tr>
</thead>
<tbody id="Tbody001"></tbody>
</table>
</div><footer id="BodyFooter"></footer><script>const BodyHeader=dgebi("BodyHeader") , BodyDiv010=dgebi("BodyDiv010"), BodyFooter=dgebi("BodyFooter");
var Tbody001 = dgebi("Tbody001");
function f1(x){var tr=dcept(Tbody001,"tr"); dcept(tr,"td").innerText=x; dcept(tr,"td").textContent=eval(x); }
f1("window===globalThis");
f1("self===globalThis");
f1("frames===globalThis");
f1("window===self");
f1("self===frames");
f1("window===frames");
</script></html>
结果
表达式 | 结果 |
---|---|
window===globalThis | true |
self===globalThis | true |
frames===globalThis | true |
window===self | true |
self===frames | true |
window===frames | true |
以下来自MDN的引用
globalThis
全局属性 globalThis 包含全局的 this 值,类似于全局对象(global object)。
语法
globalThis
描述
在以前,从不同的 JavaScript 环境中获取全局对象需要不同的语句。在 Web 中,可以通过 window、self 或者 frames 取到全局对象,但是在 Web Workers 中,只有 self 可以。在 Node.js 中,它们都无法获取,必须使用 global。
在松散模式下,可以在函数中返回 this 来获取全局对象,但是在严格模式和模块环境下,this 会返回 undefined。 You can also use Function(‘return this’)(), but environments that disable eval(), like CSP in browsers, prevent use of Function in this way.
globalThis 提供了一个标准的方式来获取不同环境下的全局 this 对象(也就是全局对象自身)。不像 window 或者 self 这些属性,它确保可以在有无窗口的各种环境下正常工作。所以,你可以安心的使用 globalThis,不必担心它的运行环境。为便于记忆,你只需要记住,全局作用域中的 this 就是 globalThis。
HTML 与 WindowProxy
在很多引擎中, globalThis 被认为是真实的全局对象的引用,但是在浏览器中,由于 iframe 以及跨窗口安全性的考虑,它实际引用的是真实全局对象(不可以被直接访问)的 Proxy 代理。在通常的应用中,很少会涉及到代理与对象本身的区别,但是也需要加以注意。
命名
并没有采用一些更常见的命名方式类似 self 和 global 是因为考虑到前向兼容,为了避免影响到现存代码的正常工作。