📌  相关文章
📜  ReferenceError: globalThis is not defined - 不管是什么(1)

📅  最后修改于: 2023-12-03 14:47:03.392000             🧑  作者: Mango

ReferenceError: globalThis is not defined - 不管是什么

当你在 ECMAScript 2020 中使用 globalThis,如果使用的 JavaScript 引擎不支持该语言功能,则会出现 ReferenceError: globalThis is not defined 错误。本文将介绍该错误的原因以及如何解决该问题。

错误原因

globalThis 是在 ECMAScript 2020 中引入的新的全局属性。它可以在所有环境中访问全局对象(例如浏览器环境中的 window 对象或 Node.js 环境中的 global 对象)。

然而,如果你使用的 JavaScript 引擎不支持该语言功能,代码会在运行时抛出 ReferenceError,指出 globalThis 未定义。这通常在较老的浏览器中发生,例如 Internet Explorer、Safari 和 iOS Safari 中。

解决方案
1. 手动添加全局对象

你可以手动将 globalThis 添加为全局对象,以解决该问题。这可以通过以下代码完成:

(function() {
  if (typeof globalThis === 'object') return;
  Object.defineProperty(Object.prototype, '__magic__', {
    get: function() {
      return this;
    },
    configurable: true // This makes it possible to `delete` the getter later.
  });
  __magic__.globalThis = __magic__; // lolwat
  delete Object.prototype.__magic__;
})();

这段代码可以在运行时检测是否存在 globalThis,如果不存在则将其添加到全局对象中。

2. 使用 polyfill 库

你可以使用可靠的 polyfill 库来填补环境中缺失的 ECMAScript 2020 特性。以下是一些流行的 polyfill 库:

将一个 polyfill 库添加到项目依赖中是解决该问题的最简单方法之一。

结论

ReferenceError: globalThis is not defined 错误通常在较老的浏览器和环境中发生。为了解决该问题,可以使用 polyfill 库或手动添加全局对象。