Appearance
编程风格
块级作用域
- let 取代 var
var命令存在变量提升效用,let命令没有这个问题
- 全局常量和线程安全
在 let 和 const 之间,优先使用 const,尤其是在全局环境,不应该设置变量,只应设置常量。
const 相较于 let
提示变量不可变
符合函数式编程思想,运算时不改变值,只新建值
JavaScript 编译器会对 const 进行优化
字符串
静态字符串一律使用单引号或反引号,不使用双引号
js
// bad
const a = 'foobar'
const b = 'foo' + a + 'bar'
// acceptable
const c = `foobar`
// good
const a = 'foobar'
const b = `foo${a}bar`解构赋值
数组成员对变量赋值时,优先使用解构赋值
js
const [first, second] = arr函数的参数如果是对象的成员,优先使用解构赋值
js
function getFullName({ firstName, lastName }) {}返回多个值,优先使用对象的解构赋值,而不是数组的解构赋值。这样扩展性更强。
js
function processInput(input) {
return { left, right, top, bottom }
}
const { left, right } = processInput(input)对象
单行定义的对象,最后一个成员不以逗号结尾。多行定义的对象,最后一个成员以逗号结尾
js
const a = { k1: v1, k2: v2 }
const b = {
k1: v1,
k2: v2
}对象尽量静态化,一旦定义,就不得随意添加新的属性。如果添加属性不可避免,要使用 Object.assign 方法
js
const a = {}
Object.assign(a, { x: 3 })使用属性表达式定义动态变量
js
const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true
}对象的属性和方法,采用简洁表达法
js
var ref = 'some value'
// bad
const atom = {
ref: ref,
value: 1,
addValue: function (value) {
return atom.value + value
}
}
// good
const atom = {
ref,
value: 1,
addValue(value) {
return atom.value + value
}
}数组
使用扩展运算符(...)拷贝数组
js
// bad
const len = items.length
const itemsCopy = []
let i
for (i = 0; i < len; i++) {
itemsCopy[i] = items[i]
}
// good
const itemsCopy = [...items]使用 Array.from 方法,将类似数组的对象转为数组
js
const foo = document.querySelectorAll('.foo')
const nodes = Array.from(foo)函数
立即执行函数可以写成箭头函数的形式
js
;(() => {
console.log('Welcome to the Internet.')
})()匿名函数当作参数的场合,尽量用箭头函数代替。更简洁,并且绑定了 this
js
// bad
;[1, 2, 3].map(function (x) {
return x * x
})
// good
;[1, 2, 3].map((x) => {
return x * x
})
// best
;[1, 2, 3].map((x) => x * x)箭头函数取代 Function.prototype.bind,不应再用 self/_this/that 绑定 this
js
// bad
const self = this
const boundMethod = function (...params) {
return method.apply(self, params)
}
// acceptable
const boundMethod = method.bind(this)
// best
const boundMethod = (...params) => method.apply(this, params)配置项都应该集中在一个对象,放在最后一个参数,布尔值不可以直接作为参数
js
// bad
function divide(a, b, option = false) {}
// good
function divide(a, b, { option = false } = {}) {}不要在函数体内使用 arguments 变量,使用 rest 运算符(...)代替。
js
// bad
function concatenateAll() {
const args = Array.prototype.slice.call(arguments)
return args.join('')
}
// good
function concatenateAll(...args) {
return args.join('')
}使用默认值语法设置函数参数的默认值
js
// bad
function handleThings(opts) {
opts = opts || {}
}
// good
function handleThings(opts = {}) {
// ...
}Map 结构
Map 和 Object 取舍:需要 key: value 的数据结构,使用 Map 结构
js
let map = new Map(arr)
for (let key of map.keys()) {
console.log(key)
}
for (let value of map.values()) {
console.log(value)
}
for (let item of map.entries()) {
console.log(item[0], item[1])
}Class
Class,取代需要 prototype 的操作
js
// bad
function Queue(contents = []) {
this._queue = [...contents]
}
Queue.prototype.pop = function () {
const value = this._queue[0]
this._queue.splice(0, 1)
return value
}
// good
class Queue {
constructor(contents = []) {
this._queue = [...contents]
}
pop() {
const value = this._queue[0]
this._queue.splice(0, 1)
return value
}
}使用 extends 实现继承
js
// bad
const inherits = require('inherits')
function PeekableQueue(contents) {
Queue.apply(this, contents)
}
inherits(PeekableQueue, Queue)
PeekableQueue.prototype.peek = function () {
return this._queue[0]
}
// good
class PeekableQueue extends Queue {
peek() {
return this._queue[0]
}
}模块
使用 import 取代 require()
js
// CommonJS 的写法
const moduleA = require('moduleA')
const func1 = moduleA.func1
const func2 = moduleA.func2
// ES6 的写法
import { func1, func2 } from 'moduleA'export 取代 module.exports
js
// commonJS 的写法
var React = require('react')
var Breadcrumbs = React.createClass({
render() {
return <nav />
}
})
module.exports = Breadcrumbs
// ES6 的写法
import React from 'react'
class Breadcrumbs extends React.Component {
render() {
return <nav />
}
}
export default Breadcrumbs只有一个输出值,就使用 export default。输出多个值,多个值为平等关系,export 和 export default 不要同时使用,除非一个值很重要。
模块默认输出一个函数,函数名的首字母应该小写,表示这是一个工具方法
js
function makeStyleGuide() {}
export default makeStyleGuide模块默认输出一个对象,对象名的首字母应该大写,表示这是一个配置值对象
js
const StyleGuide = {
es6: {}
}
export default StyleGuideESLint 的使用
ESLint 是一个语法规则和代码风格的检查工具,可以用来保证写出语法正确、风格统一的代码。
安装 eslint
bash
npm install --save-dev eslint安装 Airbnb 语法规则,以及 import、a11y、react 插件
bash
npm install --save-dev eslint-config-airbnb
npm install --save-dev eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react项目根目录下新建一个.eslintrc 文件,配置 ESLint
json
{
"extends": "eslint-config-airbnb"
}