no-global-assign
不允许分配给原生对象或只读全局变量
在 配置文件 中使用来自 @eslint/js
的 recommended
配置可以启用此规则
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.
此规则的错误代码示例:
¥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
var 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 中引入。