版本

vars-on-top

要求 var 声明被放置在它们包含的作用域的顶部

❄️ 已冻结

此规则目前已冻结,并且不接受功能请求。

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

规则详情

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

此规则的错误代码示例

在 Playground 中打开
/*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++) {}
}
在 Playground 中打开
/*eslint vars-on-top: "error"*/

// Variable declaration after other statements:
f();
var a;
在 Playground 中打开
/*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;
    }

}

此规则的正确代码示例

在 Playground 中打开
/*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++) {}
}
在 Playground 中打开
/*eslint vars-on-top: "error"*/

var a;
f();
在 Playground 中打开
/*eslint vars-on-top: "error"*/

class C {

    static {
        var a;
        if (something) {
            a = true;
        }
    }

    static {
        var a;
        f();
    }

}
在 Playground 中打开
/*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 中引入。

深入阅读

资源

更改语言