vars-on-top
要求 var
声明放在其包含范围的顶部
当变量声明没有在函数范围的顶部或程序的顶部连续使用时,vars-on-top
规则会生成警告。默认情况下,JavaScript 解释器总是将变量声明不可见地移动(“提升”)到其包含范围的顶部。此规则强制程序员通过手动将变量声明移动到其包含范围的顶部来表示该行为。
¥The vars-on-top
rule generates warnings when variable declarations are not used serially at the top of a function scope or the top of a program.
By default variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter.
This rule forces the programmer to represent that behavior by manually moving the variable declaration to the top of its containing scope.
规则详情
¥Rule Details
该规则旨在将所有变量声明保留在前导语句系列中。允许多个声明有助于提高可维护性,因此是允许的。
¥This rule aims to keep all variable declarations in the leading series of statements. Allowing multiple declarations helps promote maintainability and is thus allowed.
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint vars-on-top: "error"*/
// Variable declaration in a nested block, and a variable declaration after other statements:
function doSomething() {
if (true) {
var first = true;
}
var second;
}
// Variable declaration in for initializer:
function doSomethingElse() {
for (var i=0; i<10; i++) {}
}
/*eslint vars-on-top: "error"*/
// Variable declaration after other statements:
f();
var a;
/*eslint vars-on-top: "error"*/
// Variables in class static blocks should be at the top of the static blocks.
class C {
// Variable declaration in a nested block:
static {
if (something) {
var a = true;
}
}
// Variable declaration after other statements:
static {
f();
var a;
}
}
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint vars-on-top: "error"*/
function doSomething() {
var first;
var second; //multiple declarations are allowed at the top
if (true) {
first = true;
}
}
function doSomethingElse() {
var i;
for (i=0; i<10; i++) {}
}
/*eslint vars-on-top: "error"*/
var a;
f();
/*eslint vars-on-top: "error"*/
class C {
static {
var a;
if (something) {
a = true;
}
}
static {
var a;
f();
}
}
/*eslint vars-on-top: "error"*/
// Directives may precede variable declarations.
"use strict";
var a;
f();
// Comments can describe variables.
function doSomething() {
// this is the first var.
var first;
// this is the second var.
var second
}
版本
此规则是在 ESLint v0.8.0 中引入。