ES6(ECMAScript 2015)是 JavaScript 历史上最重要的更新之一,引入了大量新特性。本文将详细介绍这些特性及其使用场景。
let 和 const
ES6 引入了块级作用域的变量声明方式:
1 2 3 4 5 6 7 8 9 10 11 12 13
| let count = 0; count = 1;
const PI = 3.14159;
{ let blockScoped = '只在块内有效'; }
|
箭头函数
箭头函数提供了更简洁的语法,并且不绑定 this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| function add(a, b) { return a + b; }
const add = (a, b) => a + b;
const double = x => x * 2;
class Timer { constructor() { this.seconds = 0; setInterval(() => { this.seconds++; }, 1000); } }
|
解构赋值
数组解构
1 2 3 4 5 6 7 8 9 10
| const [a, b, c] = [1, 2, 3];
let x = 1, y = 2; [x, y] = [y, x];
const [first, second = 'default'] = [1];
|
对象解构
1 2 3 4 5 6 7 8 9 10 11 12
| const person = { name: 'TianHang', age: 25, city: 'Shanghai' };
const { name, age } = person;
const { name: userName } = person;
const { country = 'China' } = person;
|
模板字符串
1 2 3 4 5 6 7 8 9 10 11 12 13
| const name = 'TianHang'; const greeting = `Hello, ${name}!`;
const html = ` <div class="container"> <h1>${greeting}</h1> </div> `;
const a = 10, b = 20; const result = `${a} + ${b} = ${a + b}`;
|
扩展运算符
1 2 3 4 5 6 7 8 9 10 11 12 13
| const arr1 = [1, 2, 3]; const arr2 = [...arr1, 4, 5];
const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1, c: 3 };
function sum(...numbers) { return numbers.reduce((acc, num) => acc + num, 0); } sum(1, 2, 3, 4);
|
Promise 和 Async/Await
Promise
1 2 3 4 5 6 7 8 9 10 11
| const fetchData = () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve('数据加载成功'); }, 1000); }); };
fetchData() .then(data => console.log(data)) .catch(error => console.error(error));
|
Async/Await
1 2 3 4 5 6 7 8 9
| const fetchDataAsync = async () => { try { const response = await fetch('/api/data'); const data = await response.json(); console.log(data); } catch (error) { console.error('请求失败:', error); } };
|
类 (Class)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Animal { constructor(name) { this.name = name; }
speak() { console.log(`${this.name} 发出声音`); }
static getSpecies() { return '动物'; } }
class Dog extends Animal { constructor(name, breed) { super(name); this.breed = breed; }
speak() { console.log(`${this.name} 汪汪叫`); } }
const dog = new Dog('旺财', '金毛'); dog.speak();
|
模块化
1 2 3 4 5 6 7 8 9
|
export const add = (a, b) => a + b; export default class Calculator { }
import Calculator, { add } from './utils';
|
新的数据结构
Map
1 2 3 4
| const map = new Map(); map.set('name', 'TianHang'); map.set('age', 25); console.log(map.get('name'));
|
Set
1 2
| const set = new Set([1, 2, 2, 3, 3, 3]); console.log([...set]);
|
总结
ES6+ 的新特性大大提升了 JavaScript 的开发效率和代码可读性。掌握这些特性对于现代前端开发至关重要。