参考
airbnb:https://github.com/airbnb/javascript
standard:https://standardjs.com/rules.html
Standard
禁止未引用变量
function myFunction () {
var result = something() // ✗ avoid
}
异常抛出
// ✓ ok
run(function (err) {
if (err) throw err
window.alert('done')
})
// ✗ avoid
run(function (err) {
window.alert('done')
})
三元表达式书写
// ✓ ok
var location = env.development ? 'localhost' : 'www.api.com'
// ✓ ok
var location = env.development
? 'localhost'
: 'www.api.com'
// ✗ avoid
var location = env.development ?
'localhost' :
'www.api.com'
new构造器必须大写
function animal () {}
var dog = new animal() // ✗ avoid
function Animal () {}
var dog = new Animal() // ✓ ok
对象设置了setter以后,必须设置getter
var person = {
set name (value) { // ✗ avoid
this._name = value
}
}
var person = {
set name (value) {
this._name = value
},
get name () { // ✓ ok
return this._name
}
}
禁止array构造器
var nums = new Array(1, 2, 3) // ✗ avoid
var nums = [1, 2, 3] // ✓ ok
禁止使用arguments.callee 和 arguments.caller
function foo (n) {
if (n <= 0) return
arguments.callee(n - 1) // ✗ avoid
}
function foo (n) {
if (n <= 0) return
foo(n - 1) // ✓ ok
}
删除debugger
function sum (a, b) {
debugger // ✗ avoid
return a + b
}
禁止使用delete操作符
var name
delete name // ✗ avoid
合并导入
import { myFunc1 } from 'module'
import { myFunc2 } from 'module' // ✗ avoid
import { myFunc1, myFunc2 } from 'module' // ✓ ok
禁止eval
eval( "var result = user." + propName ) // ✗ avoid
var result = user[propName] // ✓ ok
异常捕获禁止重新赋值
try {
// ...
} catch (e) {
e = 'new value' // ✗ avoid
}
try {
// ...
} catch (e) {
const newVal = 'new value' // ✓ ok
避免不必要的布尔值判断
const result = true
if (!!result) { // ✗ avoid
// ...
}
const result = true
if (result) { // ✓ ok
// ...
}
switch要写break
switch (filter) {
case 1:
doSomething() // ✗ avoid
case 2:
doSomethingElse()
}
switch (filter) {
case 1:
doSomething()
break // ✓ ok
case 2:
doSomethingElse()
}
switch (filter) {
case 1:
doSomething()
// fallthrough // ✓ ok
case 2:
doSomethingElse()
}
禁止在嵌套块中声明函数
if (authenticated) {
function setAuthUser () {} // ✗ avoid
}
new构造函数需要赋值
new Character() // ✗ avoid
const character = new Character() // ✓ ok
路径拼接
const pathToFile = __dirname + '/app.js' // ✗ avoid
const pathToFile = path.join(__dirname, 'app.js') // ✓ ok
赋值返回必须写括号
function sum (a, b) {
return result = a + b // ✗ avoid
}
function sum (a, b) {
return (result = a + b) // ✓ ok
}
异常抛出
throw 'error' // ✗ avoid
throw new Error('error') // ✓ ok
使用或代替三元
let score = val ? val : 0 // ✗ avoid
let score = val || 0 // ✓ ok
移除不必要的构造器
class Car {
constructor () { // ✗ avoid
}
}