JavaScript ES6核心特性指南

深入理解ES6新特性,提升JavaScript开发效率

ES6特性详解

ES6(ECMAScript 2015)为JavaScript带来了众多强大的新特性,本文将详细介绍这些特性的使用方法和最佳实践。

箭头函数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// 传统函数
function add(a, b) {
    return a + b;
}

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

// 箭头函数与this
const obj = {
    name: 'ES6',
    sayLater() {
        setTimeout(() => {
            console.log(this.name);
        }, 1000);
    }
};

解构赋值

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// 数组解构
const [a, b] = [1, 2];

// 对象解构
const { name, age } = { name: 'ES6', age: 6 };

// 函数参数解构
function printUser({ name, age }) {
    console.log(`${name} is ${age} years old`);
}

模板字符串

1
2
3
4
const name = 'ES6';
const greeting = `Hello, ${name}!
This is a multiline
string.`;

类和继承

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Animal {
    constructor(name) {
        this.name = name;
    }
    
    speak() {
        return `${this.name} makes a sound.`;
    }
}

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

Promise异步处理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Data fetched');
        }, 1000);
    });
}

// 使用Promise
fetchData()
    .then(data => console.log(data))
    .catch(error => console.error(error));

// async/await语法
async function getData() {
    try {
        const data = await fetchData();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}

模块化

1
2
3
4
5
6
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

// main.js
import { add, subtract } from './math';

Set和Map数据结构

1
2
3
4
5
6
7
8
// Set
const set = new Set([1, 2, 2, 3]);
console.log([...set]); // [1, 2, 3]

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

生成器函数

1
2
3
4
5
6
7
8
9
function* numberGenerator() {
    yield 1;
    yield 2;
    yield 3;
}

const gen = numberGenerator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

默认参数和剩余参数

1
2
3
4
5
6
7
8
9
// 默认参数
function greet(name = 'Guest') {
    return `Hello, ${name}!`;
}

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

Proxy代理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const handler = {
    get: function(target, name) {
        return name in target ? target[name] : 'Not found';
    }
};

const obj = new Proxy({}, handler);
obj.name = 'ES6';
console.log(obj.name);    // 'ES6'
console.log(obj.age);     // 'Not found'

掌握这些ES6特性,将帮助你写出更现代、更优雅的JavaScript代码。

使用绝夜之城强力驱动