ES6(ECMAScript 2015)是 JavaScript 語言發展史上的一個重要里程碑,它引入了許多新的語法特性和功能,提升了代碼的可讀性、可維護性和開發效率。
1. 塊級作用域變量:let 和 const
ES6 引入了 let
和 const
關鍵字,用于聲明塊級作用域的變量,解決了 var 的變量提升和全局污染問題。
// let 示例:塊級作用域
function testLet() {if (true) {let x = 10;}console.log(x); // 報錯:x 未定義
}// const 示例:常量聲明
const PI = 3.14159;
PI = 3.14; // 報錯:無法重新賦值給常量
關鍵點:
let
允許變量重新賦值,但不能重復聲明const
聲明常量,必須初始化且不能重新賦值- 兩者都具有塊級作用域(
{}
內有效)
2. 箭頭函數(Arrow Functions)
箭頭函數提供了更簡潔的函數語法,并且自動綁定 this
上下文。
// 基本語法
const sum = (a, b) => a + b;// 多行表達式需要大括號和 return
const multiply = (a, b) => {return a * b;
};// 無參數時使用空括號
const sayHello = () => console.log('Hello!');// 自動綁定 this
class Counter {constructor() {this.count = 0;}increment = () => {this.count++; // 箭頭函數保留 this 上下文}
}
優勢:
- 語法更簡潔,省去
function
和return
關鍵字 - 不綁定自己的
this
,繼承自父級作用域 - 適合簡單的回調函數和需要保留上下文的場景
3. 模板字符串(Template Literals)
模板字符串使用反引號(`),支持變量插值和多行字符串。
const name = 'Alice';
const age = 30;// 變量插值
const greeting = `Hello, ${name}! You are ${age} years old.`;// 多行字符串
const message = `This is a multi-linestring using template literals.
`;// 表達式計算
const total = `The total is ${10 + 20}.`;
4. 解構賦值(Destructuring Assignment)
解構賦值允許從數組或對象中提取值并賦值給變量。
// 數組解構
const numbers = [1, 2, 3];
const [a, b, c] = numbers; // a=1, b=2, c=3// 對象解構
const person = {firstName: 'John',lastName: 'Doe',age: 30
};
const { firstName, age } = person; // firstName='John', age=30// 別名和默認值
const { firstName: name, city = 'Unknown' } = person;
5. 擴展運算符(Spread Operator)
擴展運算符(...
)可以展開數組或對象。
// 數組擴展
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]// 合并數組
const merged = [...arr1, ...arr2]; // [1, 2, 1, 2, 3, 4]// 對象擴展
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }// 函數參數展開
const numbers = [1, 2, 3];
console.log(Math.max(...numbers)); // 3
6. 類(Class)和繼承
ES6 引入了類的語法糖,基于原型實現面向對象編程。
// 類定義
class Animal {constructor(name) {this.name = name;}speak() {console.log(`${this.name} makes a sound.`);}
}// 繼承
class Dog extends Animal {constructor(name) {super(name); // 調用父類構造函數}speak() {console.log(`${this.name} barks.`);}
}const dog = new Dog('Buddy');
dog.speak(); // "Buddy barks."
注意:
- 類是原型繼承的語法糖
- 使用
extends
關鍵字實現繼承 constructor
方法用于初始化對象super()
調用父類的構造函數或方法
7. Promise 對象
Promise 用于處理異步操作,解決回調地獄問題。
// Promise 基本用法
const fetchData = new Promise((resolve, reject) => {setTimeout(() => {const data = { name: 'John', age: 30 };resolve(data); // 操作成功// reject(new Error('Failed to fetch data')); // 操作失敗}, 1000);
});// 使用 Promise
fetchData.then(data => console.log(data)).catch(error => console.error(error));// Promise 鏈式調用
fetchData.then(data => processData(data)).then(result => displayResult(result)).catch(error => handleError(error));
8. 模塊化:import 和 export
ES6 引入了官方的模塊系統,替代了 CommonJS 和 AMD。
// 導出模塊
// utils.js
export const PI = 3.14159;
export function calculateCircleArea(radius) {return PI * radius * radius;
}// 導入模塊
// main.js
import { PI, calculateCircleArea } from './utils.js';
console.log(calculateCircleArea(5));// 導入整個模塊
import * as utils from './utils.js';
console.log(utils.PI);// 默認導出
// logger.js
export default function log(message) {console.log(`[LOG] ${message}`);
}// 導入默認導出
import log from './logger.js';
log('This is a message');
9. 默認參數值
函數參數可以設置默認值,當參數未傳遞時使用默認值。
function greet(name = 'Guest') {console.log(`Hello, ${name}!`);
}greet(); // "Hello, Guest!"
greet('Alice'); // "Hello, Alice!"
10. 剩余參數(Rest Parameters)
剩余參數允許將不確定數量的參數收集為一個數組。
function sum(...numbers) {return numbers.reduce((total, num) => total + num, 0);
}console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15
11. Map 和 Set 數據結構
ES6 引入了新的數據結構 Map
和 Set
,提供了更高效的數據存儲和查找方式。
// Map 示例:鍵值對集合
const myMap = new Map();
myMap.set('name', 'John');
myMap.set(1, 'One');console.log(myMap.get('name')); // "John"
console.log(myMap.size); // 2// Set 示例:唯一值集合
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2); // 重復值會被忽略console.log(mySet.has(1)); // true
console.log(mySet.size); // 2
特點:
Map
:鍵可以是任意類型,保持插入順序,提供高效的查找Set
:值唯一,自動去重,提供高效的成員檢測
12. 迭代器(Iterators)和 for…of 循環
迭代器是一種接口,為各種不同的數據結構提供統一的訪問機制。
// 數組迭代
const numbers = [1, 2, 3];
for (const num of numbers) {console.log(num); // 1, 2, 3
}// 字符串迭代
const str = 'hello';
for (const char of str) {console.log(char); // 'h', 'e', 'l', 'l', 'o'
}// 自定義迭代器
const myIterable = {[Symbol.iterator]() {let i = 0;return {next() {return i < 3 ? { value: i++, done: false } : { done: true };}};}
};for (const value of myIterable) {console.log(value); // 0, 1, 2
}
13. 生成器(Generators)
生成器是一種特殊的函數,可以暫停執行并在需要時恢復。
// 生成器函數
function* countNumbers() {let i = 0;while (true) {yield i++;}
}const counter = countNumbers();
console.log(counter.next().value); // 0
console.log(counter.next().value); // 1
console.log(counter.next().value); // 2// 生成器用于迭代
function* evenNumbers() {let i = 0;while (i < 10) {yield i;i += 2;}
}for (const num of evenNumbers()) {console.log(num); // 0, 2, 4, 6, 8
}
關鍵點:
- 使用
function*
定義生成器函數 yield
關鍵字暫停函數執行并返回值- 生成器對象實現了迭代器接口
總結
ES6 的這些新特性極大地提升了 JavaScript 的表達能力和開發效率,使代碼更加簡潔、優雅和易于維護。本文介紹了 ES6 中最核心的特性,包括塊級作用域、箭頭函數、模板字符串、解構賦值、擴展運算符、類和繼承、Promise、模塊化等,以及補充的 Map/Set 數據結構、迭代器和生成器。