ES6新特性

145 阅读2分钟

ES6(ECMAScript 2015)引入了许多新特性,显著提升了 JavaScript 的功能和开发效率,以下是一些主要的新特性:

1. 块级作用域

  • let 和 constlet 声明的变量具有块级作用域,不存在变量提升;const 用于声明常量,一旦声明必须赋值,且不能再重新赋值(对于引用类型,虽然不能重新赋值,但可以修改其内部属性)。
{
    let x = 10;
    const y = 20;
    // x 和 y 仅在这个块级作用域内有效
}

2. 箭头函数

  • 提供了更简洁的函数定义语法,并且没有自己的 thisargumentssuper 或 new.target,它的 this 值继承自外层函数。
const sum = (a, b) => a + b;

3. 模板字符串

  • 使用反引号()来定义,可以包含占位符 ${}`,方便进行字符串拼接。
const name = 'John';
const message = `Hello, ${name}!`;

4. 解构赋值

  • 可以从数组或对象中提取值,并赋值给变量。
// 数组解构
const [a, b] = [1, 2];
// 对象解构
const { foo, bar } = { foo: 'value1', bar: 'value2' };

5. 默认参数值

  • 允许在函数定义时为参数提供默认值。
function greet(name = 'Guest') {
    return `Hello, ${name}!`;
}

6. 扩展运算符

  • 可以将数组或对象展开。
// 数组展开
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4];
// 对象展开
const obj1 = { a: 1, b: 2 };
const obj2 = {...obj1, c: 3 };

7. 类和继承

  • 引入了 class 关键字,用于创建类,使用 extends 关键字实现继承,使面向对象编程更加直观。
class Animal {
    constructor(name) {
        this.name = name;
    }
    speak() {
        console.log(`${this.name} makes a noise.`);
    }
}

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

8. Promise 对象

  • 用于处理异步操作,避免回调地狱,提供了更清晰的异步编程方式。
const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('Success');
    }, 1000);
});

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

9. 模块化

  • 引入了 import 和 export 关键字,用于实现模块化开发,使代码更易于维护和复用。
// 导出模块
export const add = (a, b) => a + b;
// 导入模块
import { add } from './math.js';

10.迭代器与生成器(Iterators & Fenerators)

// 生成器函数 
function* idGenerator() {
    let id = 1; 
    while (true) {
        yield id++; 
    }
}
const gen = idGenerator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

11.Set和Map

// Set(去重集合)
const numbers = new Set([1, 2, 2, 3]); // {1, 2, 3}
// Map(键值对集合,键可以是任意类型)
const map = new Map();
map.set("name", "Alice");
map.get("name"); // "Alice"

12.Symbol类型

const uniqueKey = Symbol('description');
const obj = { [uniqueKey]: "私有属性值" };
console.log(obj[uniqueKey]); // "私有属性值"

13.Proxy和Reflect

const target = {};
const handler = { 
    get: (obj, prop) => prop in obj ? obj[prop] : '默认值'
}; 
const proxy = new Proxy(target, handler);
console.log(proxy.name); // '默认值'