es6基本编程风格
1. 块级作用域,
-
let 替代var
-
优先使用const
-
所有的函数都应该设置为常量
2.字符串
静态字符串一律使用单引号或反引号,不使用双引号。动态字符串使用反引号。
const str = 'abc';
const str = `qqq${a}bbb`
3.解构赋值
- 使用数组成员对变量进行赋值时, 优先使用结构赋值。
const arr = [ 1, 2, 3, 4 ]
const [ a, b, c, d ] = arr
- 函数的参数如果有对象的成员时,优先使用结构赋值
const obj = {
firstName: 'aaa',
lastName: 'bbb',
}
function getFullName ({firstName, lastName} = obj) {
console.log(firstName, lastName)
}
- 函数有多个返回值,优先使用对象的结构赋值,而不是数组的结构赋值,这样便于以后添加返回值,以及更改返回值的顺序。
这样做的原因在于结构赋值的实质在于模式匹配,对象更易于匹配。
function processInput() {
const left = 1
const right = 2
const top = 3
const bottom = 5
return [ left, right, top, bottom ]
}
function processInput () {
return { left: '1', right: '2', top: '3', bottom: '4' }
}
const [ left, bottom, right ] = processInput()
console.log(left, bottom)
4.对象
- 单行定义的对象,最后一个成员不以逗号结尾,多行定义的对象,最后一个成员以逗号结尾。
//bad
const a = { k1: v1, k2: v2, }
const b = {
k1: v1,
k2: v2
}
//good
const a = { k1: v1, k2: v2 }
const b = {
k1: v1,
k2: v2,
}
- 对象前后有空格, : 符号前面不空格,后面空格
//bad
const c = {kq: kw } || { k2: k1}
const d = { k1:k2 }
//good
const f = { kq: k1 }
- 对象尽量动态化,一旦定义就不能随意添加新的属性,如果添加属性不可避免,要使用Object.assign方法。
// bad
const a = {}
a.x = 3
// good
const b = {}
Object.assign( b, { x: 3 } )
// good
const a = { x: null }
a.x = 3
- 如果对象的属性名是动态的,可以在创造对象的时候,使用属性表达式定义(也有人叫做对象的计算属性)
// bad
const obj = {
id: 5,
name: 'Kobe',
}
obj[getKey('enabled')] = true
// good
const obj = {
id: 5,
name: 'Kobe',
[getKey('enabled')]: true
}
- 对象的属性和方法,尽量采用简洁表达式,易于描述和书写。
// bad
let ref = 'some value'
const atom = {
ref: ref,
value: 1,
addValue: function (value) {
return value * 2
},
}
// good
const atom = {
ref,
addValue () {
return value * 2
},
}
5.数组
- 使用扩展运算符拷贝数组
// bad
const len = items.length
const itemsCopy = []
let i
for (let i = 0; i < len; i++) {
itemsCopyp[i] = items[i]
}
// good
const itemsCopy = [...items]
- 使用Array.from 方法,将类数组的对象转为数组。
const foo = document.querySelectorAll('.foo')
const nodes = Array.from(foo)
6.函数
- 函数的格式
function name () {
}
- 在使用匿名参数当参数的场合,尽量用箭头函数代替。
// 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)
7.导入导出
- 使用import 代替 require,使用export取代 module.exports。
// bad
const moduleA = require('moduleA')
const func1 = moduleA.func1
const func2 = moduleA.func2
// good
import { func1, func2 } from 'moduleA'
import React from 'react'
class Breadcrumbs extends React.Component {
render() {
retrun <nav />
}
}
export default Breadcrumbs
- 如果模块默认输出一个函数,函数名的首字母应该小写,
function makeStyleGuide () {}
export default makeStyleGuide
- 当导出多个函数时,应写成对象的模式
export default {
async functionA () {
},
functionB () {
},
}
- 如果模块默认输出一个对象,对象名的首字母应该大写。
const StyleGuide = {
es6: {
}
}
export default StyleGuide