JavaScript 全局this globalThis 笔记

测试代码

<!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===globalThistrue
self===globalThistrue
frames===globalThistrue
window===selftrue
self===framestrue
window===framestrue

以下来自MDN的引用

globalThis

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 是因为考虑到前向兼容,为了避免影响到现存代码的正常工作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kfepiza

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值