Eslint
规则 | Rules

no-inner-declarations

不允许function嵌套块中的变量或声明( no-inner-declarations )

"extends": "eslint:recommended"配置文件中的属性启用此规则。

在 ES6 之前的 JavaScript 中,函数声明只允许在程序的第一级或其他函数的主体中使用,尽管解析器有时会在其他地方错误地接受它们。这仅适用于函数声明; 命名或匿名函数表达式可以发生在允许表达式的任何位置。

// Good function doSomething() { } // Bad if (test) { function doSomethingElse () { } } function anotherThing() { var fn; if (test) { // Good fn = function expression() { }; // Bad function declaration() { } } }

变量声明可以在语句可以运行的任何位置使用,甚至可以嵌套在其他模块内部。由于变量提升,这通常是不希望的,将声明移动到程序或函数体的根部可以增加清晰度。请注意,块绑定(letconst)未被挂起,因此它们不受此规则影响。

/*eslint-env es6*/ // Good var foo = 42; // Good if (foo) { let bar1; } // Bad while (test) { var bar2; } function doSomething() { // Good var baz = true; // Bad if (baz) { var quux; } }

规则细节

这条规则要求函数声明和可选的变量声明位于程序的根节点或函数的主体中。

选项

这条规则有一个字符串选项:

  • "functions"(默认)不允许function嵌套块中的声明

  • "both"在嵌套块中禁止functionvar声明

功能

此规则的默认代码错误代码示例"functions"

/*eslint no-inner-declarations: "error"*/ if (test) { function doSomething() { } } function doSomethingElse() { if (test) { function doAnotherThing() { } } }

具有默认选项的此规则的正确代码示例"functions"

/*eslint no-inner-declarations: "error"*/ function doSomething() { } function doSomethingElse() { function doAnotherThing() { } } if (test) { asyncCall(id, function (err, data) { } } var fn; if (test) { fn = function fnExpression() { }; }

both

此规则的错误代码示例包含以下"both"选项:

/*eslint no-inner-declarations: ["error", "both"]*/ if (test) { var foo = 42; } function doAnotherThing() { if (test) { var bar = 81; } }

此规则的正确代码示例包含以下"both"选项:

/*eslint no-inner-declarations: "error"*/ /*eslint-env es6*/ var bar = 42; if (test) { let baz = 43; } function doAnotherThing() { var baz = 81; }

何时不使用它

函数声明部分规则在块范围函数着陆在 ES6 中时将被渲染为废弃,但在此之前,它应该保留以强制执行有效的构造。在使用 block-scoped-var 时禁用检查变量声明或者在嵌套块中声明变量尽管提升仍然可接受。

版本

这条规则是在 ESLint 0.6.0 中引入的。

资源