block-scoped-var

在定义的范围内强制使用变量

当变量在定义它们的块之外使用时,block-scoped-var 规则会生成警告。这模拟了 C 风格的块作用域。

¥The block-scoped-var rule generates warnings when variables are used outside of the block in which they were defined. This emulates C-style block scope.

规则详情

¥Rule Details

该规则旨在减少变量在其绑定上下文之外的使用,并模仿其他语言的传统块作用域。这是为了帮助该语言的新手避免变量提升的困难错误。

¥This rule aims to reduce the usage of variables outside of their binding context and emulate traditional block scope from other languages. This is to help newcomers to the language avoid difficult bugs with variable hoisting.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint block-scoped-var: "error"*/

function doIf() {
    if (true) {
        var build = true;
    }

    console.log(build);
}

function doIfElse() {
    if (true) {
        var build = true;
    } else {
        var build = false;
    }
}

function doTryCatch() {
    try {
        var build = 1;
    } catch (e) {
        var f = build;
    }
}

function doFor() {
    for (var x = 1; x < 10; x++) {
        var y = f(x);
    }
    console.log(y);
}

class C {
    static {
        if (something) {
            var build = true;
        }
        build = false;
    }
}

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint block-scoped-var: "error"*/

function doIf() {
    var build;

    if (true) {
        build = true;
    }

    console.log(build);
}

function doIfElse() {
    var build;

    if (true) {
        build = true;
    } else {
        build = false;
    }
}

function doTryCatch() {
    var build;
    var f;

    try {
        build = 1;
    } catch (e) {
        f = build;
    }
}

function doFor() {
    for (var x = 1; x < 10; x++) {
        var y = f(x);
        console.log(y);
    }
}

class C {
    static {
        var build = false;
        if (something) {
            build = true;
        }
    }
}

版本

此规则是在 ESLint v0.1.0 中引入。

进阶读物

资源

ESLint 中文网
粤ICP备13048890号