vars-on-top

要求将 var 声明放在其包含范围的顶部

当变量声明没有在函数范围的顶部或程序的顶部连续使用时,vars-on-top 规则会生成警告。默认情况下,变量声明总是被 JavaScript 解释器不可见地移动(“提升”)到其包含范围的顶部。此规则强制程序员通过手动将变量声明移动到其包含范围的顶部来表示该行为。

规则详情

该规则旨在将所有变量声明保留在前导语句系列中。允许多个声明有助于提高可维护性,因此是允许的。

此规则的错误代码示例:

/*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 doSomething() {
    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;
    }

}

此规则的正确代码示例:

/*eslint vars-on-top: "error"*/

function doSomething() {
    var first;
    var second; //multiple declarations are allowed at the top
    if (true) {
        first = true;
    }
}

function doSomething() {
    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
}