globalThis
试一试
function canMakeHTTPRequest() {
return typeof globalThis.XMLHttpRequest === "function";
}
console.log(canMakeHTTPRequest());
// Expected output (in a browser): true
值
全局 this 对象。
globalThis 的属性特性 | |
|---|---|
| 可写 | 是 |
| 可枚举 | 否 |
| 可配置 | 是 |
注意: globalThis 属性是可配置和可写的,这样代码作者可以在执行不受信任的代码时隐藏它,并防止暴露全局对象。
描述
历史上,在不同的 JavaScript 环境中访问全局对象需要不同的语法。在 Web 上,你可以使用 window、self 或 frames——但在 Web Workers 中,只有 self 会起作用。在 Node.js 中,这些都不起作用,你必须改用 global。this 关键字可以在非严格模式下运行的函数内部使用,但在模块和严格模式下运行的函数内部,this 将是 undefined。你也可以使用 Function('return this')(),但禁用 eval() 的环境(如浏览器中的 CSP)会阻止以这种方式使用 Function。
globalThis 属性提供了一种跨环境访问全局 this 值(从而访问全局对象本身)的标准方式。与 window 和 self 等类似属性不同,它保证在窗口和非窗口上下文中都能工作。通过这种方式,你可以以一致的方式访问全局对象,而无需知道代码正在哪个环境中运行。为了帮助你记住这个名字,只需记住在全局作用域中,this 值就是 globalThis。
注意: globalThis 通常与全局对象是相同的概念(即,向 globalThis 添加属性会使它们成为全局变量)——浏览器和 Node 都是如此——但宿主可以为 globalThis 提供一个与全局对象无关的不同值。
HTML 和 WindowProxy
在许多引擎中,globalThis 将是实际全局对象的引用,但在 Web 浏览器中,由于 iframe 和跨窗口安全考虑,它引用的是实际全局对象(你无法直接访问)的 Proxy。这种区别在常见用法中很少相关,但了解这一点很重要。
命名
其他几个流行的命名选择,如 self 和 global,由于它们可能与现有代码产生兼容性问题而被排除。有关更多详细信息,请参阅语言提案的“命名”文档。
globalThis 字面上就是全局 this 值。它与非严格模式下未通过对象调用的函数中的 this 值相同。它也是脚本全局作用域中的 this 值。
示例
跨环境搜索全局对象
通常,全局对象不需要显式指定——它的属性会自动作为全局变量访问。
console.log(window.Math === Math); // true
然而,需要显式访问全局对象的一个情况是向其写入,通常是为了polyfill的目的。
在 globalThis 之前,获取环境全局对象的唯一可靠跨平台方法是 Function('return this')()。然而,这在某些设置中会导致 CSP 违规,因此作者会使用这样的分段定义(略微改编自原始 core-js 源代码)
function check(it) {
// Math is known to exist as a global in every environment.
return it && it.Math === Math && it;
}
const globalObject =
check(typeof window === "object" && window) ||
check(typeof self === "object" && self) ||
check(typeof global === "object" && global) ||
// This returns undefined when running in strict mode
(function () {
return this;
})() ||
Function("return this")();
获取全局对象后,我们可以在其上定义新的全局变量。例如,添加 Intl 的实现
if (typeof globalObject.Intl === "undefined") {
// No Intl in this environment; define our own on the global scope
Object.defineProperty(globalObject, "Intl", {
value: {
// Our Intl implementation
},
enumerable: false,
configurable: true,
writable: true,
});
}
有了 globalThis,就不再需要跨环境额外搜索全局对象了。
if (typeof globalThis.Intl === "undefined") {
Object.defineProperty(globalThis, "Intl", {
value: {
// Our Intl implementation
},
enumerable: false,
configurable: true,
writable: true,
});
}
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-globalthis |
浏览器兼容性
加载中…