Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. JavaScript 标准内置对象
  5. globalThis

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

globalThis

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2020年1月⁩.

全局属性globalThis 包含全局的this 值,类似于全局对象(global object)。

尝试一下

function canMakeHTTPRequest() {  return typeof globalThis.XMLHttpRequest === "function";}console.log(canMakeHTTPRequest());// Expected output (in a browser): true
globalThis 的属性特性
可写
可枚举
可配置

语法

globalThis

描述

在以前,从不同的 JavaScript 环境中获取全局对象需要不同的语句。在 Web 中,可以通过windowself 或者frames 取到全局对象,但是在Web Workers 中,只有self 可以。在 Node.js 中,它们都无法获取,必须使用global

在松散模式下,可以在函数中返回this 来获取全局对象,但是在严格模式和模块环境下,this 会返回undefined。你也可以使用Function('return this')(),但那些禁用eval()的环境,如在浏览器中的CSP,不允许这样使用Function

globalThis 提供了一个标准的方式来获取不同环境下的全局this 对象(也就是全局对象自身)。不像window 或者self 这些属性,它确保可以在有无窗口的各种环境下正常工作。所以,你可以安心的使用globalThis,不必担心它的运行环境。为便于记忆,你只需要记住,全局作用域中的this 就是globalThis

HTML 与 WindowProxy

在很多引擎中,globalThis 被认为是真实的全局对象的引用,但是在浏览器中,由于 iframe 以及跨窗口安全性的考虑,它实际引用的是真实全局对象(不可以被直接访问)的Proxy 代理。在通常的应用中,很少会涉及到代理与对象本身的区别,但是也需要加以注意。

命名

并没有采用一些更常见的命名方式,如selfglobal,这是为了避免影响现存代码的兼容性。更多相关信息可以查看language proposal's "naming" document

示例

globalThis 之前,获取某个全局对象的唯一方式就是Function('return this')(),但是这在某些情况下会违反CSP 规则,所以,es6-shim 使用了类似如下的方式:

js
var getGlobal = function () {  if (typeof self !== "undefined") {    return self;  }  if (typeof window !== "undefined") {    return window;  }  if (typeof global !== "undefined") {    return global;  }  throw new Error("unable to locate global object");};var globals = getGlobal();if (typeof globals.setTimeout !== "function") {  // 此环境中没有 setTimeout 方法!}

但是有了globalThis 之后,只需要:

js
if (typeof globalThis.setTimeout !== "function") {  //  此环境中没有 setTimeout 方法!}

规范

Specification
ECMAScript® 2026 Language Specification
# sec-globalthis

浏览器兼容性

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp