ES6+常用特性

77 阅读3分钟

ES6+新特性

JavaScript在版本更新中逐步添加了很多好用的新特性。 下面会梳理一下从ES6到ES12都有哪些常用的新特性。

ES6

类(class)

class rectangle{
    constructor(height, width) {
        this.area = height*width;
    }

    outputArea(){
        return this.area;
    }
}

class square extends rectangle{
    constructor(height, width, length){
        super(height, width);
        this.length = length;
    }
}

let a = new rectangle(15, 30);

let b = new square(10, 10, 10);
console.log(a.outputArea());
console.log(b.outputArea());
console.log(b.length);

箭头函数

let a = (x, y) => x * y
let b = (x, y) => {
    x = x+2;
    y = y+4;
    return x*y;
 }

console.log(a(3,5));
console.log(b(2,4));

模块化(ES module)

export const sub = (a, b) => a + b //导出声明
export {func1 , func2} //导出列表
export default function func3(){} //默认导出
export fun4 as f4 from 'module-name' //导出模块合集

import {func1, func2} from 'module-name' //具名导入
import defaultExport from // 默认导入
import * as myModule from 'module-name' //命名空间导入
import 'module-name' //副作用导入

函数参数默认值

function sub(a, b=15) {
    return a + b;
}

console.log(sub(10, 30)) //output: 40
console.log(sub(10)) //output; 25

模板字符串

const name = 'ice';
const str = `Your name is ${name}`
console.log(str) //"Your name is ice"

解构赋值

let a, b, rest;
[a,b] = [10,20];
console.log(a); //10
console.log(b); //20

[a,b] = [b,a];
console.log(a); //20
console.log(b); //10

Promise

const p = new Promise((resolve, reject) => {
    resolve(1);
}).then((val) => {
    console.log(val);
})

var、let、const

var 全局作用域,后续声明的同名变量会覆盖前一个。
let 块级作用域,不能重复声明同一个命名的变量。
const 块级作用域,不能重复声明同一个命名的变量,且变量声明后不能重新赋值。

ES7

Array.prototype.includes

let four = 4;
let arr = ['a', 'b', 3, four]
console.log(arr.includes('a')) //true
console.log(arr.includes(3)) //true
console.log(arr.includes(four)) //true
console.log(arr.includes(4)) //true
console.log(arr.includes('c')) //false

幂运算(**)

let a = 5**2 // 25
let b = Math.pow(5, 2) //25

ES8

Async、 Await

const asyncFun = async () => {
    await new Promise((resolve, reject) => {
        new setTimeout(() => {resolve(3)}, 3000)
    }).then(val => console.log(val))
    console.log(4)
    await new Promise((resolve, reject) => {
        reject(5)
    }).catch(val => console.log(val))
}

aysncFun()

// output:
// 3 
// 4
// 5

Object.entries

let obj = {name: "mark", age: "26"}
console.log(Object.entries(obj)) // [['name', 'mark'],['age','26']]

Object.values

let obj = {name: "mark", age: "26"}
console.log(Object.values(obj)) // ['mark', '26']

Object.getOwnPropertyDescriptors

let obj = {name: "mark", age: "26"}
console.log(Object.getOwnPropertyDescriptors(obj))
//Object { name: Object { value: "mark", writable: true, enumerable: true, configurable: true }, age: Object { value: "26", writable: true, enumerable: true, configurable: true }}

String.prototype.padStart()

let str='abc'
console.log(str.padStart(5)) // '  abc'
console.log(str.padStart(5, 'x'))// 'xxabc'
console.log(str.padStart(5, 'xyz'))// 'xyabc'
console.log(str.padStart(7, 'xyz'))// 'xyzxabc'
console.log(str.padStart(1))// 'abc'

String.prototype.padEnd()

let str='abc'
console.log(str.padEnd(5)) // 'abc  '
console.log(str.padEnd(5, 'x'))// 'abcxx'
console.log(str.padEnd(5, 'xyz'))// 'abcxy'
console.log(str.padEnd(7, 'xyz'))// 'abcxyzx'
console.log(str.padEnd(1))// 'abc'

ES9

异步迭代(AsyncIterator)

let p = function(val, time){
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(val)
        }, time)
    })
}

let asyncI = async function* asyncIterator(){
   yield await p(1, 10000);
   yield await p(2, 1000);
   yield await p(3, 100);
}

async function main(){
	for await (const i of asyncI()){
    	console.log(i)
	}
}

main()

展开运算符

function sum(a, b, c){
    return a+b+c;
}
let args = [1,2,3];
console.log(sum(...args)) // 6

promise.catch()

new Promise((resolve, reject) => {
    reject('reject')
}).catch((str) => {
    console.log(str) // reject
})

promise.finally()

new Promise((resolve, reject) => {
    resolve('resolve')
}).then((str) => {
    console.log(str) // resolve
}).finally(() => { 
    console.log('finally') // resolve
})

ES10

Array.prototype.flat() / flatMap()

const arr = [1, [2, 3, [4, 5]]];
console.log(arr.flat()); // [1, 2, 3, [4, 5]]
console.log(arr.flat(2)); // [1, 2, 3, 4, 5]
console.log(arr.flat(Infinity)); // [1, 2, 3, 4, 5]

console.log(arr.flatMap((i) => i > 2)) //[false, false]

Object.fromEntries()

let arr = [['a', 1], ['b', 2]];
const obj = Object.fromEntries(arr);
console.log(obj) // { a: 1, b: 2 }

String.prototype.trimStart() / trimEnd()

let str = '  123   '
console.log(str.trimStart()) // '123   '
console.log(str.trimEnd()) // '  123'

Symbol.prototype.description

const obj = Symbol('test');
console.log(obj.description); // 'test'

Function.prototype.toString()

function name(str) {
    return str
}

console.log(name.toString())
/*
"function name(str) {
    return str
}"
*/ 

ES11

可选链(?.)

class person{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }

    inputName(){
        return this.name;
    }
}

let p1 = new person("mark", 16);
console.log(p1.inputName()); //mark
console.log(p1.inputAge?.()); //undefined
console.log(p1?.height); //undefined
            
console.log(p1.inputName()); //mark
console.log(p1.inputAge()); //Error: p1.inputAge is not a function

空值合并运算符(??)

const name = null ?? "mark";
const age = 22 ?? 16;
console.log(name) // mark
console.log(age) // 22

globalThis

// 浏览器中
console.log(globalThis === window); // true

// Node.js 中
console.log(globalThis === global); // true

// Web Worker 中
console.log(globalThis === self); // true

动态导入

// 传统静态导入
import lodash from 'lodash';

// 动态导入
async function loadLodash() {
  const { default: _ } = await import('lodash');
  return _;
}

promise.allSettled

const p1 = new Promise((resolve, reject) => {
    resolve(1);
})
const p2 = new Promise((resolve, reject) => {
    reject(2);
})
let arr = Promise.allSettled([p1,p2])

arr.then((results) => {
	for(let re of results){
    	console.log(re)
    }
})

// output: Object { status: "fulfilled", value: 1 }
// output: Object { status: "rejected", reason: 2 }

ES12

String.prototype.replaceAll()

const str = 'A B C D';

console.log(str.replaceAll('A', 'E')); //E B C D

Promise.any()

const P1 = new Promise((resolve, reject) => {
    reject('123');
})
const P2 = new Promise((resolve, reject) => {
    reject('345');
})
const P3 = new Promise((resolve, reject) => {
    resolve('456');
})

Promise.any([P1, P2, P3]).then(result => {
    console.log(result);  // 456
})