Eslint
规则 | Rules

no-shadow

不允许来自外部作用域中声明的阴影变量的变量声明(无阴影)

阴影是局部变量与其包含范围内的变量共享相同名称的过程。例如:

var a = 3; function b() { var a = 10; }

在这种情况下,a内部的变量b()会映射a全局范围中的变量。这会在阅读代码时造成混淆,并且无法访问全局变量。

规则细节

该规则旨在消除阴影变量声明。

此规则的错误代码示例:

/*eslint no-shadow: "error"*/ /*eslint-env es6*/ var a = 3; function b() { var a = 10; } var b = function () { var a = 10; } function b(a) { a = 10; } b(a if (true) { let a = 5; }

选项

这条规则从一个选项,对象,具有属性"builtinGlobals""hoist""allow"

{ "no-shadow": ["error", { "builtinGlobals": false, "hoist": "functions", "allow": [] }] }

builtinGlobals

builtinGlobals选项是false默认的。如果它是true:,该规则防止在内置全局变量的阴影ObjectArrayNumber,等等。

选项的错误代码示例{ "builtinGlobals": true }

/*eslint no-shadow: ["error", { "builtinGlobals": true }]*/ function foo() { var Object = 0; }

hoist

hoist选项有三个设置:

  • functions (默认情况下) - 在定义外部函数之前报告遮蔽。

  • all - 在定义外部变量/函数之前报告所有阴影。

  • never - 在定义外部变量/函数之前从不报告阴影。

hoist: functions

不正确的代码为默认{ "hoist": "functions" }选项的示例:

/*eslint no-shadow: ["error", { "hoist": "functions" }]*/ /*eslint-env es6*/ if (true) { let b = 6; } function b() {}

虽然let bif声明中是在外部作用域中的函数声明之前,但它是不正确的。

默认选项的正确代码示例{ "hoist": "functions" }

/*eslint no-shadow: ["error", { "hoist": "functions" }]*/ /*eslint-env es6*/ if (true) { let a = 3; } let a = 5;

因为let a在声明中在外部范围中if变量声明之前,所以是正确的。

hoist: all

选项的错误代码示例{ "hoist": "all" }

/*eslint no-shadow: ["error", { "hoist": "all" }]*/ /*eslint-env es6*/ if (true) { let a = 3; let b = 6; } let a = 5; function b() {}

hoist: never

选项的正确代码示例{ "hoist": "never" }

/*eslint no-shadow: ["error", { "hoist": "never" }]*/ /*eslint-env es6*/ if (true) { let a = 3; let b = 6; } let a = 5; function b() {}

因为let a并且let bif声明中是在外部范围的声明之前,所以它们是正确的。

allow

allow选项是允许进行遮蔽的标识符名称的数组。例如"resolve""reject""done""cb"

选项的正确代码示例{ "allow": ["done"] }

/*eslint no-shadow: ["error", { "allow": ["done"] }]*/ /*eslint-env es6*/ import async from 'async'; function foo(done) { async.map([1, 2], function (e, done) { done(null, e * 2) }, done } foo(function (err, result) { console.log{ err, result } }

Further Reading

  • no-shadow-restricted-names

版本

该规则在 ESLint 0.0.9 中引入。

资源