本文根据 Devhints / ES2015+ 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2019-11-14。
快速概览 ES2015、ES2016、ES2017、ES2018 及后续版本中引入的 JavaScript 新特性。
块级作用域
Let
function fn () {
let x = 0
if (true) {
let x = 1 // only inside this `if`
}
}
Const
const a = 1
let 是新的 var。常量(Constants)的工作方式与 let类似,但不能被重新赋值。请参阅: Let 和 const
反引号字符串(模板字符串)
插值
const message = `Hello ${name}`
多行字符串
const str = `
hello
world
`
模板与多行字符串。参见: 模板字符串
二进制和八进制字面量
let bin = 0b1010010
let oct = 0o755
参见: 二进制和八进制字面量
新方法
新的字符串方法
"hello".repeat(3)
"hello".includes("ll")
"hello".startsWith("he")
"hello".padStart(8) // " hello"
"hello".padEnd(8) // "hello "
"hello".padEnd(8, '!') // hello!!!
"\u1E9B\u0323".normalize("NFC")
参见: 新方法
类
class Circle extends Shape {
构造函数
constructor (radius) {
this.radius = radius
}
方法
getArea () {
return Math.PI * 2 * this.radius
}
调用父类方法
expand (n) {
return super.expand(n) * Math.PI
}
静态方法
static createFromDiameter(diameter) {
return new Circle(diameter / 2)
}
}
原型的语法糖。参见: 类
幂运算符
const byte = 2 ** 8
// Same as: Math.pow(2, 8)
Promise 异步处理
创建 Promise
new Promise((resolve, reject) => {
if (ok) { resolve(result) }
else { reject(error) }
})
用于异步编程。参见: Promise 异步处理
使用 Promise
promise
.then((result) => { ··· })
.catch((error) => { ··· })
结合 `finally` 使用 Promise
promise
.then((result) => { ··· })
.catch((error) => { ··· })
.finally(() => { // logic independent of success/error })
当 Promise 状态变为已完成(fulfilled)或已拒绝(rejected)时,会调用相应的处理程序。
Promise 相关函数
Promise.all(···)
Promise.race(···)
Promise.reject(···)
Promise.resolve(···)
Async-await
async function run () {
const user = await getUser()
const tweets = await getTweets(user)
return [user, tweets]
}
async 这是使用函数的一种新方式。
解构
解构赋值
数组
const [first, last] = ['Nikola', 'Tesla']
对象
let {title, author} = {
title: 'The Silkworm',
author: 'R. Galbraith'
}
支持对数组和对象进行匹配。参见: 解构
默认值
const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores
// Result:
// math === 22, sci === 33, arts === 50
在解构数组或对象时,可以指定默认值。
函数参数
function greet({ name, greeting }) {
console.log(`${greeting}, ${name}!`)
}
greet({ name: 'Larry', greeting: 'Ahoy' })
在函数参数中也可以进行对象和数组的解构。
默认值
function greet({ name = 'Rauno' } = {}) {
console.log(`Hi ${name}!`);
}
greet() // Hi Rauno!
greet({ name: 'Larry' }) // Hi Larry!
重命名键(属性名)
function printCoordinates({ left: x, top: y }) {
console.log(`x: ${x}, y: ${y}`)
}
printCoordinates({ left: 25, top: 90 })
此示例将……赋值给…… x ……的值 left 关键所在。
循环
for (let {title, artist} of songs) {
···
}
赋值表达式同样适用于循环。
对象解构
const { id, ...detail } = song;
使用剩余(rest,即 `…`)运算符,单独提取部分键,并将对象中剩余的键归为一组
展开(Spread)
对象展开
使用对象展开
const options = {
...defaults,
visible: true
}
不使用对象展开
const options = Object.assign(
{}, defaults,
{ visible: true })
对象展开运算符允许你基于现有对象构建新对象。
参见: 对象展开
数组展开
使用数组展开
const users = [
...admins,
...editors,
'rstacruz'
]
不使用数组展开
const users = admins
.concat(editors)
.concat([ 'rstacruz' ])
展开运算符同样允许你基于现有数组构建新数组。
参见: 展开运算符
函数
函数参数
默认参数
function greet (name = 'Jerry') {
return `Hello ${name}`
}
剩余参数
function fn(x, ...y) {
// y is an Array
return x * y.length
}
展开(Spread)
fn(...[1, 2, 3])
// same as fn(1, 2, 3)
默认参数、剩余参数、展开运算符。参见: 函数参数
箭头函数(Fat arrows)
箭头函数(Fat arrows)
setTimeout(() => {
···
})
带参数
readFile('text.txt', (err, data) => {
...
})
隐式返回
numbers.map(n => n * 2)
// No curly braces = implicit return
// Same as: numbers.map(function (n) { return n * 2 })
numbers.map(n => ({
result: n * 2
}))
// Implicitly returning objects requires parentheses around the object
类似于函数,但 this (上下文)得以保留。参见: 箭头函数(Fat arrows)
对象
简写语法
module.exports = { hello, bye }
// Same as: module.exports = { hello: hello, bye: bye }
参见: 对象字面量增强
方法
const App = {
start () {
console.log('running')
}
}
// Same as: App = { start: function () {···} }
参见: 对象字面量增强
Getter 和 Setter
const App = {
get closed () {
return this.status === 'closed'
},
set closed (value) {
this.status = value ? 'closed' : 'open'
}
}
参见: 对象字面量增强
计算属性名
let event = 'click'
let handlers = {
[`on${event}`]: true
}
// Same as: handlers = { 'onclick': true }
参见: 对象字面量增强
提取值
const fatherJS = { age: 57, name: "Brendan Eich" }
Object.values(fatherJS)
// [57, "Brendan Eich"]
Object.entries(fatherJS)
// [["age", 57], ["name", "Brendan Eich"]]
模块
导入
import 'helpers'
// aka: require('···')
import Express from 'express'
// aka: const Express = require('···').default || require('···')
import { indent } from 'helpers'
// aka: const indent = require('···').indent
import * as Helpers from 'helpers'
// aka: const Helpers = require('···')
import { indentSpaces as indent } from 'helpers'
// aka: const indent = require('···').indentSpaces
import 是新的 require()。参见: 模块导入
导出
export default function () { ··· }
// aka: module.exports.default = ···
export function mymethod () { ··· }
// aka: module.exports.mymethod = ···
export const pi = 3.14159
// aka: module.exports.pi = ···
export 是新的 module.exports。参见: 模块导出
生成器(Generators)
生成器(Generators)
function* idMaker () {
let id = 0
while (true) { yield id++ }
}
let gen = idMaker()
gen.next().value // → 0
gen.next().value // → 1
gen.next().value // → 2
情况比较复杂。参见: 生成器(Generators)
For..of 迭代
for (let i of iterable) {
···
}
用于遍历生成器和数组。参见: For..of 迭代