noInnerDeclarations
诊断类别:lint/correctness/noInnerDeclarations
¥Diagnostic Category: lint/correctness/noInnerDeclarations
自从:v1.0.0
¥Since: v1.0.0
来源:
¥Sources:
-
与以下相同:
no-inner-declarations
¥Same as:
no-inner-declarations
禁止在其块外可访问的 function
和 var
声明。
¥Disallow function
and var
declarations that are accessible outside their block.
var
可在最近的根(函数、模块、脚本、静态块)的整个主体中访问。为了避免混淆,应将它们声明为最近的根。
¥A var
is accessible in the whole body of the nearest root (function, module, script, static block).
To avoid confusion, they should be declared to the nearest root.
在 ES2015 之前,function
声明仅允许在最近的根中使用,尽管解析器有时会错误地在其他地方接受它们。在 ES2015 中,在 ES 模块内部,function
声明始终是块范围的。
¥Prior to ES2015, function
declarations were only allowed in the nearest root,
though parsers sometimes erroneously accept them elsewhere.
In ES2015, inside an ES module, a function
declaration is always block-scoped.
请注意,const
和 let
声明是块范围的,因此它们不受此规则的影响。此外,ES 模块内允许嵌套块中的 function
声明。
¥Note that const
and let
declarations are block-scoped,
and therefore they are not affected by this rule.
Moreover, function
declarations in nested blocks are allowed inside ES modules.
¥Examples
¥Invalid
code-block.cjs:2:5 lint/correctness/noInnerDeclarations ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This function should be declared at the root of the script.
1 │ if (test) {
> 2 │ function f() {}
│ ^^^^^^^^^^^^^^^
3 │ }
4 │
ℹ The function is accessible in the whole body of the script.
To avoid confusion, it should be declared at the root of the script.
code-block.js:2:5 lint/correctness/noInnerDeclarations ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This var should be declared at the root of the module.
1 │ if (test) {
> 2 │ var x = 1;
│ ^^^^^^^^^
3 │ }
4 │
ℹ The var is accessible in the whole body of the module.
To avoid confusion, it should be declared at the root of the module.
code-block.cjs:3:9 lint/correctness/noInnerDeclarations ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This function should be declared at the root of the enclosing function.
1 │ function f() {
2 │ if (test) {
> 3 │ function g() {}
│ ^^^^^^^^^^^^^^^
4 │ }
5 │ }
ℹ The function is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.
code-block.js:3:9 lint/correctness/noInnerDeclarations ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This var should be declared at the root of the enclosing function.
1 │ function f() {
2 │ if (test) {
> 3 │ var x = 1;
│ ^^^^^^^^^
4 │ }
5 │ }
ℹ The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.
¥Valid
¥Related links