Disallow Early Use (no-use-before-define)

禁止定义前使用 (no-use-before-define)

In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it’s possible to use identifiers before their formal declarations in code. This can be confusing and some believe it is best to always declare variables and functions before using them.

在 ES6 标准之前的 JavaScript 中,某个作用域中变量和函数的声明会被提前到作用域顶部,所以可能存在这种情况:此变量在声明前被使用。这会扰乱读者,部分人认为最好的做法是使用变量之前先声明变量。

In ES6, block-level bindings (let and const) introduce a “temporal dead zone” where a ReferenceError will be thrown with any attempt to access the variable before its declaration.

在 ES6 中,块级绑定 (letconst) 引入 “temporal dead zone”,当企图使用未声明的变量会抛出 ReferenceError

Rule Details

This rule will warn when it encounters a reference to an identifier that has not yet been declared.

当使用一个还未声明的标示符是会报警告。

Examples of incorrect code for this rule:

错误 代码示例:

/*eslint no-use-before-define: "error"*/
/*eslint-env es6*/

alert(a);
var a = 10;

f();
function f() {}

function g() {
    return b;
}
var b = 1;

{
    alert(c);
    let c = 1;
}

Examples of correct code for this rule:

正确 代码示例:

/*eslint no-use-before-define: "error"*/
/*eslint-env es6*/

var a;
a = 10;
alert(a);

function f() {}
f(1);

var b = 1;
function g() {
    return b;
}

{
    let c;
    c++;
}

Options

{
    "no-use-before-define": ["error", { "functions": true, "classes": true }]
}

This rule accepts "nofunc" string as an option. "nofunc" is the same as { "functions": false, "classes": true }.

该规则接受 "nofunc" 字符串作为一个选项。 "nofunc"{ "functions": false, "classes": true } 的效果相同。

functions

Examples of correct code for the { "functions": false } option:

选项{ "functions": false }正确 代码示例:

/*eslint no-use-before-define: ["error", { "functions": false }]*/

f();
function f() {}

classes

Examples of incorrect code for the { "classes": false } option:

选项{ "classes": false }错误 代码示例:

/*eslint no-use-before-define: ["error", { "classes": false }]*/
/*eslint-env es6*/

new A();
class A {
}

Examples of correct code for the { "classes": false } option:

选项{ "classes": false }正确 代码示例:

/*eslint no-use-before-define: ["error", { "classes": false }]*/
/*eslint-env es6*/

function foo() {
    return new A();
}

class A {
}

variables

Examples of incorrect code for the { "variables": false } option:

选项 { "variables": false }错误 代码示例:

/*eslint no-use-before-define: ["error", { "variables": false }]*/

console.log(foo);
var foo = 1;

Examples of correct code for the { "variables": false } option:

选项 { "variables": false }正确 代码示例:

/*eslint no-use-before-define: ["error", { "variables": false }]*/

function baz() {
    console.log(foo);
}

var foo = 1;

Version

This rule was introduced in ESLint 0.0.9.

该规则在 ESLint 0.0.9 中被引入。

Resources