Index

no-global-assign

不允许分配给原生对象或只读全局变量

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

JavaScript 环境包含许多内置的全局变量,例如浏览器中的 window 和 Node.js 中的 process。在几乎所有情况下,你都不希望为这些全局变量赋值,因为这样做可能导致无法访问重要的功能。例如,你可能不希望在浏览器代码中这样做:

🌐 JavaScript environments contain a number of built-in global variables, such as window in browsers and process in Node.js. In almost all cases, you don’t want to assign a value to these global variables as doing so could result in losing access to important functionality. For example, you probably don’t want to do this in browser code:

window = {};

虽然像 window 这样的例子显而易见,但 JavaScript 环境通常提供数百个内置的全局对象。很难判断你是否在给全局变量赋值。

🌐 While examples such as window are obvious, there are often hundreds of built-in global objects provided by JavaScript environments. It can be hard to know if you’re assigning to a global variable or not.

规则详情

🌐 Rule Details

此规则不允许修改只读全局变量。

🌐 This rule disallows modifications to read-only global variables.

ESLint 能够将全局变量配置为只读。

🌐 ESLint has the capability to configure global variables as read-only.

另请参阅:指定全局

🌐 See also: Specify Globals

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint no-global-assign: "error"*/

Object = null
undefined = 1
在线运行
/*eslint no-global-assign: "error"*/
/*global window:readonly*/

window = {}

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*eslint no-global-assign: "error"*/

a = 1
let b = 1
b = 2
在线运行
/*eslint no-global-assign: "error"*/
/*global onload:writable*/

onload = function() {}

选项

🌐 Options

此规则接受一个 exceptions 选项,可用于指定允许重新分配的内置列表:

🌐 This rule accepts an exceptions option, which can be used to specify a list of builtins for which reassignments will be allowed:

{
    "rules": {
        "no-global-assign": ["error", {"exceptions": ["Object"]}]
    }
}

何时不使用

🌐 When Not To Use It

如果你试图覆盖原生对象之一。

🌐 If you are trying to override one of the native objects.

版本

此规则是在 ESLint v3.3.0 中引入。

资源