《ES6新特性》

110 阅读1分钟

1. let 和 const

// 块级作用域
let x = 10;
const PI = 3.14;

{
    let x = 20; // 不会影响外部的x
    const y = 30;
}

2. 箭头函数

// 传统函数
function add(a, b) {
    return a + b;
}

// 箭头函数
const add = (a, b) => a + b;

// this指向不同
const obj = {
    name: 'test',
    sayTraditional: function() {
        setTimeout(function() {
            console.log(this.name); // undefined
        }, 100);
    },
    sayArrow: function() {
        setTimeout(() => {
            console.log(this.name); // 'test'
        }, 100);
    }
};

3. 解构赋值

// 数组解构
const [a, b] = [1, 2];

// 对象解构
const { name, age } = { name: 'John', age: 30 };

// 带默认值的解构
const { title = 'Default' } = {};

// 嵌套解构
const { address: { city } } = person;

4. 模板字符串

const name = 'John';
const greeting = `Hello ${name}!
This is a multiline
string`;

5. 扩展运算符

// 数组展开
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];

// 对象展开
const obj1 = { foo: 'bar', x: 42 };
const obj2 = { ...obj1, y: 13 };

// 函数参数
const numbers = [1, 2, 3];
console.log(Math.max(...numbers));

6. Promise

const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('success');
    }, 1000);
});

promise
    .then(result => console.log(result))
    .catch(error => console.error(error));

// async/await (ES2017)
async function fetchData() {
    try {
        const result = await promise;
        console.log(result);
    } catch (error) {
        console.error(error);
    }
}

7. 类(Class)

class Animal {
    constructor(name) {
        this.name = name;
    }
    
    speak() {
        return `${this.name} makes a sound`;
    }
}

class Dog extends Animal {
    speak() {
        return `${this.name} barks`;
    }
}

8. 模块化

// 导出
export const PI = 3.14;
export function square(x) {
    return x * x;
}

// 默认导出
export default class User {
    // ...
}

// 导入
import { PI, square } from './math.js';
import User from './user.js';

9. Map 和 Set

// Map
const map = new Map();
map.set('key', 'value');
map.get('key');

// Set
const set = new Set([1, 2, 3, 3]); // 自动去重

10. 默认参数

function greet(name = 'Guest') {
    return `Hello ${name}!`;
}

11. Object 新方法

// Object.assign
const target = { a: 1 };
const source = { b: 2 };
const result = Object.assign(target, source);

// Object.keys/values/entries
const obj = { a: 1, b: 2 };
Object.keys(obj);    // ['a', 'b']
Object.values(obj);  // [1, 2]
Object.entries(obj); // [['a', 1], ['b', 2]]

12. Array 新方法

// includes
[1, 2, 3].includes(2); // true

// find/findIndex
[1, 2, 3].find(x => x > 1);     // 2
[1, 2, 3].findIndex(x => x > 1); // 1

// Array.from
Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']

13. 可选链操作符(ES2020)

const user = {
    address: {
        street: 'Main St'
    }
};

// 旧写法
const street = user && user.address && user.address.street;

// 新写法
const street = user?.address?.street;

14. 空值合并操作符(ES2020)

const foo = null ?? 'default'; // 'default'
const bar = 0 ?? 'default';    // 0

15. BigInt(ES2020)

const bigInt = 9007199254740991n;
const result = bigInt + 1n;