globalThis

globalThis 全局属性包含 全球 this 值,该值通常类似于 全局对象

¥The globalThis global property contains the global this value, which is usually akin to the global object.

Try it

¥Value

全局 this 对象。

¥The global this object.

Property attributes of globalThis
Writable yes
Enumerable no
Configurable yes

注意:globalThis 属性是可配置和可写的,以便代码作者可以在执行不受信任的代码时隐藏它并防止公开全局对象。

¥Note: The globalThis property is configurable and writable so that code authors can hide it when executing untrusted code and prevent exposing the global object.

描述

¥Description

从历史上看,在不同的 JavaScript 环境中访问全局对象需要不同的语法。在网络上你可以使用 windowselfframes - 但在 Web 工作线程 中只有 self 可以工作。在 Node.js 中,这些都不起作用,你必须使用 globalthis 关键字可以在非严格模式下运行的函数内部使用,但 this 在模块中以及在严格模式下运行的内部函数中将是 undefined。你也可以使用 Function('return this')(),但禁用 eval() 的环境(例如浏览器中的 CSP)会阻止以这种方式使用 Function

¥Historically, accessing the global object has required different syntax in different JavaScript environments. On the web you can use window, self, or frames - but in Web Workers only self will work. In Node.js none of these work, and you must instead use global. The this keyword could be used inside functions running in non–strict mode, but this will be undefined in modules and inside functions running in strict mode. 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 值(以及全局对象本身)的标准方法。与 windowself 等类似属性不同,它保证在窗口和非窗口上下文中工作。这样,你就可以以一致的方式访问全局对象,而无需知道代码运行在哪个环境中。为了帮助你记住该名称,只需记住在全局范围内 this 值是 globalThis 即可。

¥The globalThis property provides a standard way of accessing the global this value (and hence the global object itself) across environments. Unlike similar properties such as window and self, it's guaranteed to work in window and non-window contexts. In this way, you can access the global object in a consistent manner without having to know which environment the code is being run in. To help you remember the name, just remember that in global scope the this value is globalThis.

注意:globalThis 通常与全局对象是相同的概念(即向 globalThis 添加属性使它们成为全局变量) - 浏览器和 Node 就是这种情况 - 但允许主机为 globalThis 提供与全局对象无关的不同值。

¥Note: globalThis is generally the same concept as the global object (i.e. adding properties to globalThis makes them global variables) — this is the case for browsers and Node — but hosts are allowed to provide a different value for globalThis that's unrelated to the global object.

HTML 和 WindowProxy

¥HTML and the WindowProxy

在许多引擎中,globalThis 将是对实际全局对象的引用,但在 Web 浏览器中,出于 iframe 和跨窗口安全考虑,它引用实际全局对象周围的 Proxy(你无法直接访问)。这种区别在常见用法中很少相关,但需要注意。

¥In many engines globalThis will be a reference to the actual global object, but in web browsers, due to iframe and cross-window security considerations, it references a Proxy around the actual global object (which you can't directly access). This distinction is rarely relevant in common usage, but important to be aware of.

命名

¥Naming

其他几个流行的名称选择(例如 selfglobal)已被排除在考虑范围之外,因为它们可能会破坏与现有代码的兼容性。有关详细信息,请参阅 语言提案的 "naming" 文件

¥Several other popular name choices such as self and global were removed from consideration because of their potential to break compatibility with existing code. See the language proposal's "naming" document for more details.

从字面上看,globalThis 是全局 this 值。它与不带对象调用的非严格函数中的 this 值相同。它也是脚本全局范围内 this 的值。

¥globalThis is, quite literally, the global this value. It's the same value as the this value in a non-strict function called without an object. It's also the value of this in the global scope of a script.

示例

¥Examples

跨环境搜索全局

¥Search for the global across environments

通常,全局对象不需要显式指定 - 它的属性可以作为全局变量自动访问。

¥Usually, the global object does not need to be explicitly specified — its properties are automatically accessible as global variables.

js
console.log(window.Math === Math); // true

然而,一种需要显式访问全局对象的情况是在写入时,通常是出于 polyfills 的目的。

¥However, one case where one needs to explicitly access the global object is when writing to it, usually for the purpose of polyfills.

globalThis 之前,获取环境的全局对象的唯一可靠的跨平台方法是 Function('return this')()。然而,这会在某些设置中导致 CSP 违规,因此作者将使用像这样的分段定义(稍微改编自 原始 core-js 源代码):

¥Prior to globalThis, the only reliable cross-platform way to get the global object for an environment was Function('return this')(). However, this causes CSP violations in some settings, so authors would use a piecewise definition like this (slightly adapted from the original core-js source):

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 的实现:

¥After obtaining the global object, we can define new globals on it. For example, adding an implementation for Intl:

js
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,就不再需要额外搜索全局跨环境:

¥With globalThis available, the additional search for the global across environments is not necessary anymore:

js
if (typeof globalThis.Intl === "undefined") {
  Object.defineProperty(globalThis, "Intl", {
    value: {
      // Our Intl implementation
    },
    enumerable: false,
    configurable: true,
    writable: true,
  });
}

规范

Specification
ECMAScript Language Specification
# sec-globalthis

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看