no-var
需要 let
或 const
而不是 var
此规则报告的一些问题可通过 --fix
命令行选项自动修复
ECMAScript 6 允许程序员使用 let
和 const
关键字创建具有块作用域而不是函数范围的变量。块作用域在许多其他编程语言中很常见,可以辅助程序员避免错误,例如:
¥ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let
and const
keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes
such as:
var count = people.length;
var enoughFood = count > sandwiches.length;
if (enoughFood) {
var count = sandwiches.length; // accidentally overriding the count variable
console.log("We have " + count + " sandwiches for everyone. Plenty for all!");
}
// our count variable is no longer accurate
console.log("We have " + count + " people and " + sandwiches.length + " sandwiches!");
规则详情
¥Rule Details
该规则旨在阻止使用 var
,并鼓励使用 const
或 let
。
¥This rule is aimed at discouraging the use of var
and encouraging the use of const
or let
instead.
示例
¥Examples
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint no-var: "error"*/
var x = "y";
var CONFIG = {};
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint no-var: "error"*/
let x = "y";
const CONFIG = {};
何时不使用
¥When Not To Use It
除了非 ES6 环境之外,如果从 var
迁移到 let
的成本太高,则开始将 ES6 引入其代码库的现有 JavaScript 项目可能不想应用此规则。
¥In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their
codebase may not want to apply this rule if the cost of migrating from var
to let
is too costly.
版本
此规则是在 ESLint v0.12.0 中引入。