JavaScript ES6新特性详解


JavaScript ES6+新特性详解

ECMAScript 6(ES6)于2015年发布,是JavaScript语言历史上最大的一次更新。此后每年都有新版本发布(ES7-ES13),统称为ES6+。这些新特性极大地改变了JavaScript的编程方式,让代码更简洁、更安全、更易维护。本文将系统介绍最重要的新特性及其在实际开发中的应用。

一、let与const:块级作用域

var有变量提升和函数作用域的问题,let和const完美解决了这些问题:

// var的问题
for (var i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 100); // 3,3,3
}

// let解决
for (let i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 100); // 0,1,2
}

// const常量 - 引用不可变,但对象属性可变
const API_URL = "https://api.example.com";
const config = { timeout: 5000 };
config.timeout = 10000;  // 允许
config = {};             // TypeError

二、箭头函数与this绑定

箭头函数不仅语法更简洁,还自动绑定了外层的this:

// 传统函数的this问题
class Timer {
    constructor() {
        this.seconds = 0;
    }
    start() {
        // 需要bind(this)或使用箭头函数
        setInterval(() => {
            this.seconds++;
            console.log(this.seconds);
        }, 1000);
    }
}

// 箭头函数简化回调
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);

三、解构赋值

解构赋值可以快速提取数组和对象中的值:

// 数组解构
const [first, second, ...rest] = [1, 2, 3, 4, 5];
// first=1, second=2, rest=[3,4,5]

// 对象解构
const { name, age, email = "default@example.com" } = user;
// 支持默认值

// 函数参数解构
function createUser({ name, age, role = "user" }) {
    return { name, age, role };
}

// 交换变量
[a, b] = [b, a];

// 嵌套解构
const { address: { city, street } } = user;

四、Promise与异步编程

Promise是处理异步操作的基础,配合async/await使异步代码像同步一样直观:

// Promise基础
function fetchUser(id) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (id > 0) {
                resolve({ id, name: "用户" + id });
            } else {
                reject(new Error("无效的ID"));
            }
        }, 1000);
    });
}

// async/await
async function getUserInfo(id) {
    try {
        const user = await fetchUser(id);
        const posts = await fetchPosts(user.id);
        const comments = await fetchComments(posts[0].id);
        return { user, posts, comments };
    } catch (error) {
        console.error("获取用户信息失败:", error);
        throw error;
    }
}

// Promise.all - 并行执行
const [users, posts, tags] = await Promise.all([
    fetchUsers(),
    fetchPosts(),
    fetchTags()
]);

五、模板字符串与标签模板

// 多行字符串和插值
const html = `
    

${user.name}

年龄: ${user.age}

`; // 标签模板 - 自定义字符串处理 function highlight(strings, ...values) { return strings.reduce((result, str, i) => { const value = values[i] ? `${values[i]}` : ""; return result + str + value; }, ""); } const keyword = "JavaScript"; const text = highlight`学习${keyword}是一件有趣的事情`;

六、类与模块

// ES6类
class Animal {
    static kingdom = "动物界";
    
    constructor(name) {
        this.name = name;
    }
    
    speak() {
        return `${this.name} makes a sound`;
    }
}

class Dog extends Animal {
    #breed;  // 私有字段
    
    constructor(name, breed) {
        super(name);
        this.#breed = breed;
    }
    
    get breed() { return this.#breed; }
    set breed(value) { this.#breed = value; }
}

// 模块导入导出
// math.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export default class Calculator { /* ... */ }

// app.js
import Calculator, { PI, add } from "./math.js";

七、其他重要特性

展开运算符与剩余参数

// 展开数组
const all = [...arr1, ...arr2, extraItem];

// 展开对象
const updated = { ...user, age: 26, city: "北京" };

// 剩余参数
function sum(...numbers) {
    return numbers.reduce((a, b) => a + b, 0);
}

Map与Set

// Map - 键值对集合
const cache = new Map();
cache.set("key", { data: [] });
cache.has("key");  // true
cache.get("key");  // { data: [] }

// Set - 唯一值集合
const unique = new Set([1, 2, 2, 3, 3]);  // Set{1,2,3}

可选链与空值合并

// 可选链 ?.
const city = user?.address?.city ?? "未知";

// 空值合并 ??
const name = user.name ?? "匿名";  // 只有null/undefined才用默认值

ES6+新特性彻底改变了JavaScript的编程范式。掌握这些特性不仅能提高开发效率,还能写出更安全、更易维护的代码。建议在实际项目中逐步采用这些新特性,体会它们带来的便利。


0.067300s