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) {
}
}
// Variable declaration in for initializer:
function doSomethingElse() {
for (; i<10; i++) {}
}
在線上測試中開啟
/*eslint vars-on-top: "error"*/
// Variable declaration after other statements:
f();
在線上測試中開啟
/*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) {
}
}
// Variable declaration after other statements:
static {
f();
}
}
此規則的正確程式碼範例
在線上測試中開啟
/*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++) {}
}
在線上測試中開啟
/*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
}
版本
此規則在 ESLint v0.8.0 中引入。
延伸閱讀

