es6 编程风格的改变
let 取代 var
let 完全可以取代 var,因为两者语义相同,而且 let 没有副作用。
在 let 和 const 之间,建议优先使用 const,尤其是在全局环境,不应该设置变量,只应设置常量。
// bad
var a = 1, b = 2, c = 3
// good
const a = 1
const b = 2
const c = 3
// best
const [a, b, c] = [1, 2, 3]
使用单引号和反引号
// bad
const a = "foobar"
const b = 'foo' + a + 'bar'
// acceptable
const c = `foobar`
// good
const a = 'foobar'
const b = `foo${a}bar`
优先使用解构赋值
const arr = [1, 2, 3, 4]
// bad
const first = arr[0]
const second = arr[1]
// good
const [first, second] = arr
单行定义的对象
最后一个成员不以逗号结尾。多行定义的对象,最后一个成员以逗号结尾。
// 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, //以逗号结尾
}
对象的属性和方法,尽量采用简洁表达法
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
},
}
使用扩展运算符(...)拷贝数组
// 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 方法,将类似数组的对象转为数组。
const foo = document.querySelectorAll('.foo')
const nodes = Array.from(foo)
立即执行函数可以写成箭头函数的形式
(() => {
console.log('Welcome to the Internet.')
})()
用匿名函数当作参数的场合,尽量用箭头函数代替。而且绑定了 this。
// 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
// 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)
配置项都应该集中在一个对象,放在最后一个参数,布尔值不可以直接作为参数。
// bad
function divide(a, b, option = false ) {}
// good
function divide(a, b, { option = false } = {}) {}
不要在函数体内使用 arguments 变量,使用 rest 运算符(...)代替。
// bad
function concatenateAll() {
const args = Array.prototype.slice.call(arguments)
return args.join('')
}
// good
function concatenateAll(...args) {
return args.join('')
}
使用默认值语法设置函数参数的默认值。
// bad
function handleThings(opts) {
opts = opts || {}
}
// good
function handleThings(opts = {}) {
// ...
}
Object 和 Map 的选择
只有模拟现实世界的实体对象时,才使用 Object。如果只是需要 key: value 的数据结构,使用 Map 结构。因为 Map 有内建的遍历机制。
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
// 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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

上一篇: es6 模块的转码
下一篇: TypeScript 常见问题
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论