Skip to content
← Back to rules

unicorn/prefer-global-this Style

💡 A suggestion is available for this rule.

作用

强制使用 globalThis 代替 特定环境的全局对象别名(windowselfglobal)。

使用标准的 globalThis 可以使你的代码在浏览器、Web Workers、Node.js, 以及未来的 JavaScript 运行时之间保持可移植性。

为什么这不好?

可移植性 – window 只在浏览器主线程中定义,self 用于 Web Workers, 而 global 是 Node 特有的。选择错误的别名会导致代码在原始环境之外执行时发生运行时崩溃。

清晰性 – globalThis 清楚地表明你指的是全局对象本身, 而不是某个特定平台。

示例

以下是此规则的错误代码示例:

js
// 仅限浏览器
window.alert("Hi");

// 仅限 Node
if (typeof global.Buffer !== "undefined") {
}

// 仅限 Web Worker
self.postMessage("done");

以下是此规则的正确代码示例:

js
globalThis.alert("Hi");

if (typeof globalThis.Buffer !== "undefined") {
}

globalThis.postMessage("done");

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "unicorn/prefer-global-this": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/prefer-global-this": "error",
  },
});
bash
oxlint --deny unicorn/prefer-global-this

版本

此规则于 v0.16.12 中添加。

参考资料