no-shadow-restricted-names
禁止标识符隐藏受限名称
在 配置文件 中使用来自 @eslint/js
的 recommended
配置可以启用此规则
ES2020 §18.1 全局对象的值属性(globalThis
、NaN
、Infinity
、undefined
)以及严格模式限制标识符 eval
和 arguments
在 JavaScript 中被视为限制名称。将它们定义为其他含义可能会产生意想不到的后果,并使其他阅读代码的人感到困惑。例如,没有什么能阻止你写:
¥ES2020 §18.1 Value Properties of the Global Object (globalThis
, NaN
, Infinity
, undefined
) as well as strict mode restricted identifiers eval
and arguments
are considered to be restricted names in JavaScript. Defining them to mean something else can have unintended consequences and confuse others reading the code. For example, there’s nothing preventing you from writing:
const undefined = "foo";
那么在同一范围内使用的任何代码都不会得到全局 undefined
,而是具有非常不同含义的局部版本。
¥Then any code used within the same scope would not get the global undefined
, but rather the local version with a very different meaning.
规则详情
¥Rule Details
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint no-shadow-restricted-names: "error"*/
function NaN(){}
!function(Infinity){};
const undefined = 5;
try {} catch(eval){}
/*eslint no-shadow-restricted-names: "error"*/
import NaN from "foo";
import { undefined } from "bar";
class Infinity {}
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint no-shadow-restricted-names: "error"*/
let Object;
function f(a, b){}
// Exception: `undefined` may be shadowed if the variable is never assigned a value.
let undefined;
/*eslint no-shadow-restricted-names: "error"*/
import { undefined as undef } from "bar";
选项
¥Options
此规则有一个对象选项:
¥This rule has an object option:
-
"reportGlobalThis"
:true
(默认false
)会报告globalThis
的声明。¥
"reportGlobalThis"
:true
(defaultfalse
) reports declarations ofglobalThis
.
reportGlobalThis
{ "reportGlobalThis": true }
选项的错误代码示例:
¥Examples of incorrect code for the { "reportGlobalThis": true }
option:
/*eslint no-shadow-restricted-names: ["error", { "reportGlobalThis": true }]*/
const globalThis = "foo";
/*eslint no-shadow-restricted-names: ["error", { "reportGlobalThis": true }]*/
function globalThis() {}
/*eslint no-shadow-restricted-names: ["error", { "reportGlobalThis": true }]*/
import { globalThis } from "bar";
/*eslint no-shadow-restricted-names: ["error", { "reportGlobalThis": true }]*/
class globalThis {}
{ "reportGlobalThis": true }
选项的正确代码示例:
¥Examples of correct code for the { "reportGlobalThis": true }
option:
/*eslint no-shadow-restricted-names: ["error", { "reportGlobalThis": true }]*/
const foo = globalThis;
function bar() {
return globalThis;
}
import { globalThis as baz } from "foo";
相关规则
版本
此规则是在 ESLint v0.1.4 中引入。