Eslint参考手册
规则 | Rules
vars-on-top
vars-on-top
规则会在变量声明未在函数作用域顶部或程序顶部串行使用时生成警告。默认情况下,变量声明总是被JavaScript解释器无形地移动(“hoisted”)到其包含范围的顶部。此规则强制程序员通过手动将变量声明移至其包含范围的顶部来表示该行为。
规则细节
该规则旨在将所有变量声明保留在前面的一系列声明中。允许多个声明有助于提高可维护性,因此被允许。
此规则的错误代码示例:
/*eslint vars-on-top: "error"*/
// Variable declarations in a block:
function doSomething() {
var first;
if (true) {
first = true;
}
var second;
}
// Variable declaration in for initializer:
function doSomething() {
for (var i=0; i<10; i++) {}
}
/*eslint vars-on-top: "error"*/
// Variables after other statements:
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"*/
// 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
}
进一步阅读
- JavaScript Scoping and Hoisting
- var Hoisting
- A criticism of the Single Var Pattern in JavaScript, and a simple alternative
- Multiple var statements in JavaScript, not superfluous
版本
这条规则是在ESLint 0.8.0中引入的。
资源
- Rule source
- Documentation source
规则 | Rules相关

ESLint 是一个代码规范和错误检查工具,有以下几个特性。所有东西都是可以插拔的。你可以调用任意的 rule api 或者 formatter api 去打包或者定义 rule or formatter。任意的 rule 都是独立的。没有特定的 coding style,你可以自己配置。
主页 | https://eslint.org/ |
源码 | https://github.com/eslint/eslint |
发布版本 | 4.12.0 |