快速浏览 ES2015、ES2016、ES2017、ES2018 及以后的 JavaScript 新特性
function fn () {
let x = 0
if (true) {
let x = 1 // 只在这个`if`里面
}
}
const a = 1
let 是新的 var。 常量(const) 就像 let 一样工作,但不能重新分配。
请参阅:Let 和 const
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")
Number.EPSILON
Number.isInteger(Infinity) // false
Number.isNaN("NaN") // false
Math.acosh(3) // 1.762747174039086
Math.hypot(3, 4) // 5
Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2
// 返回一个真实的数组
Array.from(document.querySelectorAll("*"))
// 类似于 new Array(...),但没有特殊的单参数行为
Array.of(1, 2, 3)
请参阅: 新方法
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)
}
}
原型的语法糖。 请参阅: 类
javascript 默认字段是公共的(public),如果需要注明私有,可以使用(#)
class Dog {
#name;
constructor(name) {
this.#name = name;
}
printName() {
//只能在类内部调用私有字段
console.log(`你的名字是${this.#name}`)
}
}
const dog = new Dog("putty")
//console.log(this.#name)
//Private identifiers are not allowed outside class bodies.
dog.printName()
class ClassWithPrivate {
static #privateStaticField;
static #privateStaticFieldWithInitializer = 42;
static #privateStaticMethod() {
// …
}
}
const [first, last] = ['Nikola', 'Tesla']
let {title, author} = {
title: 'The Silkworm',
author: 'R. Galbraith'
}
支持匹配数组和对象。 请参阅:解构
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 是一个数组
return x * y.length
}
fn(...[1, 2, 3])
// 与 fn(1, 2, 3) 相同
Default(默认), rest, spread(扩展)。 请参阅:函数参数
setTimeout(() => {
···
})
readFile('text.txt', (err, data) => {
...
})
arr.map(n => n*2)
// 没有花括号 = 隐式返回
// 同: arr.map(function (n) { return n*2 })
arr.map(n => ({
result: n*2
}))
// 隐式返回对象需要在对象周围加上括号
类似函数,但保留了 this。
请参阅:箭头函数
const App = {
start () {
console.log('running')
}
}
// 同: App = { start: function () {···} }
请参阅:对象文字增强
const App = {
get closed () {
return this.status === 'closed'
},
set closed (value) {
this.status = value ? 'closed' : 'open'
}
}
请参阅:对象字面量增强
let event = 'click'
let handlers = {
[`on${event}`]: true
}
// 同: handlers = { 'onclick': true }
请参阅:对象字面量增强
import 'helpers'
// 又名: require('···')
import Express from 'express'
// 又名: const Express = require('···').default || require('···')
import { indent } from 'helpers'
// 又名: const indent = require('···').indent
import * as Helpers from 'helpers'
// 又名: const Helpers = require('···')
import { indentSpaces as indent } from 'helpers'
// 又名: const indent = require('···').indentSpaces
import 是新的 require()。
请参阅:Module imports
export default function () { ··· }
// 又名: module.exports.default = ···
export function mymethod () { ··· }
// 又名: module.exports.mymethod = ···
export const pi = 3.14159
// 又名: module.exports.pi = ···
const firstName = 'Michael';
const lastName = 'Jackson';
const year = 1958;
export { firstName, lastName, year };
export * from "lib/math";
export 是新的module.exports。
请参阅:Module exports
button.addEventListener('click', event => {
import('./dialogBox.js')
.then(dialogBox => {
dialogBox.open();
})
.catch(error => {
/* Error handling */
})
});
ES2020提案 引入 import() 函数
ES2020 为 import 命令添加了一个元属性 import.meta,返回当前模块的元信息
new URL('data.txt', import.meta.url)
Node.js 环境中,import.meta.url返回的总是本地路径,即 file:URL 协议的字符串,比如 file:///home/user/foo.js
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
let fibonacci = {
[Symbol.iterator]() {
let pre = 0, cur = 1;
return {
next() {
[pre, cur] = [cur, pre + cur];
return { done: false, value: cur }
}
}
}
}
for (var n of fibonacci) {
// 在 1000 处截断序列
if (n > 1000) break;
console.log(n);
}
用于迭代生成器和数组。 请参阅:For..of iteration