声明变量时,请使用
const
、let
关键字,如果没有写关键字,变量就会暴露在全局上下文中,这样很可能会和现有变量冲突,另外,也很难明确该变量的作用域是什么。这里推荐使用const
来声明变量,我们需要避免全局命名空间的污染。eslint: no-undef prefer-const// bad demo = new Demo() // good const demo = new Demo()
将所有的
const
和let
分组// bad let a const b let c const d let e // good const b const d let a let c let e
变量不要进行链式赋值
原因:变量链式赋值会创建隐藏的全局变量
// bad (function example() { // JavaScript interprets this as // let a = ( b = ( c = 1 ) ); // The let keyword only applies to variable a; variables b and c become // global variables. let a = b = c = 1 }()) console.log(a) // throws ReferenceError console.log(b) // 1 console.log(c) // 1 // good (function example() { let a = 1 let b = a let c = a }()) console.log(a) // throws ReferenceError console.log(b) // throws ReferenceError console.log(c) // throws ReferenceError // the same applies for `const`
不允许出现未被使用的变量,eslint: no-unused-vars
原因:声明但未被使用的变量通常是不完全重构犯下的错误.这种变量在代码里浪费空间并会给读者造成困扰
// bad var some_unused_var = 42 // Write-only variables are not considered as used. var y = 10 y = 5 // A read for a modification of itself is not considered as used. var z = 0 z = z + 1 // Unused function arguments. function getX (x, y) { return x } // good function getXPlusY (x, y) { return x + y } const x = 1 const y = a + 2 alert(getXPlusY(x, y)) // 'type' is ignored even if unused because it has a rest property sibling. // This is a form of extracting an object that omits the specified keys. const { type, ...coords } = data // 'coords' is now the 'data' object without its 'type' property.
文档更新时间: 2021-05-11 16:00 作者:姚连洲