ES6 核心語法手冊
一、變量聲明
關鍵字 | 作用域 | 是否可重定義 | 是否可修改 | 特性 |
---|---|---|---|---|
let | 塊級作用域 | ? | ? | 替代 var 的首選 |
const | 塊級作用域 | ? | ? | 聲明常量(對象屬性可修改) |
// 示例
let name = "Alice";
name = "Bob"; // ?const PI = 3.14;
// PI = 3.15; ? 報錯const user = { name: "John" };
user.name = "Mike"; // ? 對象屬性可修改
二、箭頭函數
// 傳統函數
function sum(a, b) {return a + b;
}// 箭頭函數
const sum = (a, b) => a + b;// 特性:
// 1. 無自己的 this(繼承外層上下文)
// 2. 不能用作構造函數
// 3. 無 arguments 對象// 示例:this 綁定
const obj = {value: 10,getValue: function() {setTimeout(() => {console.log(this.value); // ? 輸出 10(箭頭函數繼承 this)}, 100);}
};
三、模板字符串
const name = "Alice";
const age = 28;// 多行字符串
const bio = `姓名:${name}
年齡:${age}
職業:工程師`;// 表達式計算
console.log(`明年年齡:${age + 1}`); // 輸出:明年年齡:29// 標簽模板(高級用法)
function highlight(strings, ...values) {return strings.reduce((result, str, i) => `${result}${str}<mark>${values[i] || ''}</mark>`, '');
}
highlight`Hello ${name}`; // <mark>Hello</mark><mark>Alice</mark>
四、解構賦值
// 數組解構
const [first, second, , fourth] = [10, 20, 30, 40];
console.log(first); // 10// 對象解構
const { name, age: userAge } = { name: "Bob", age: 30 };
console.log(userAge); // 30// 函數參數解構
function getUser({ id, name = "Unknown" }) {console.log(`ID: ${id}, Name: ${name}`);
}
getUser({ id: 1 }); // ID: 1, Name: Unknown
五、擴展運算符與剩余參數
// 數組擴展
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]// 對象擴展
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }// 剩余參數
function sum(...numbers) {return numbers.reduce((acc, cur) => acc + cur, 0);
}
sum(1, 2, 3); // 6
六、類與繼承
class Animal {constructor(name) {this.name = name;}speak() {console.log(`${this.name} makes a noise`);}
}class Dog extends Animal {constructor(name, breed) {super(name);this.breed = breed;}speak() {super.speak();console.log("Woof!");}
}const rex = new Dog("Rex", "Labrador");
rex.speak();
七、模塊化
// 📁 math.js
export const PI = 3.14159;
export function square(x) { return x * x; }
export default function cube(x) { return x * x * x; }// 📁 app.js
import { PI, square } from './math.js';
import cube from './math.js'; // 導入默認導出console.log(square(PI)); // 9.8690227281
八、Promise 與異步
// 創建 Promise
const fetchData = () => new Promise((resolve, reject) => {setTimeout(() => Math.random() > 0.5 ? resolve("成功!") : reject("失敗!"), 1000);
});// 使用 Promise
fetchData().then(data => console.log(data)).catch(error => console.error(error));// Async/Await
async function getData() {try {const result = await fetchData();console.log(result);} catch (error) {console.error(error);}
}
九、新增數據結構
類型 | 特性 | 常用方法 |
---|---|---|
Set | 值唯一的集合 | add() , delete() , has() |
Map | 鍵值對集合(鍵可以是任意類型) | set() , get() , has() |
WeakSet | 弱引用集合(僅存儲對象) | add() , delete() , has() |
WeakMap | 弱引用鍵值對(鍵必須是對象) | set() , get() , has() |
// Set 示例
const uniqueNumbers = new Set([1, 2, 2, 3]);
console.log([...uniqueNumbers]); // [1, 2, 3]// Map 示例
const userMap = new Map();
userMap.set(1, { name: "Alice" });
console.log(userMap.get(1)); // { name: "Alice" }
十、其他重要特性
-
Symbol - 創建唯一標識符
const id = Symbol("uniqueID"); console.log(id === Symbol("uniqueID")); // false
-
迭代器與生成器
function* idGenerator() {let id = 1;while (true) yield id++; } const gen = idGenerator(); console.log(gen.next().value); // 1
-
Proxy 與 Reflect(元編程)
const handler = {get(target, prop) {return prop in target ? target[prop] : 37;} }; const p = new Proxy({}, handler); console.log(p.a); // 37
ES6 兼容性解決方案
- 使用 Babel 進行代碼轉換
- 配合 Webpack/Rollup 打包
- 核心特性現代瀏覽器已原生支持(可查 Can I Use)