ES6从入门到精通:其他特性
ES6 模块化
ES6 引入了标准的模块化系统,使用 import
和 export
语法。模块化可以拆分代码为多个文件,便于维护和复用。
导出模块:
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
导入模块:
// app.js
import { add, subtract } from './math.js';
console.log(add(2, 3)); // 5
默认导出:
// math.js
export default function multiply(a, b) {return a * b;
}
导入默认导出:
// app.js
import multiply from './math.js';
console.log(multiply(2, 3)); // 6
箭头函数
箭头函数提供更简洁的函数语法,并且没有自己的 this
,arguments
,super
或 new.target
。
基本语法:
const add = (a, b) => a + b;
单参数可省略括号:
const square = x => x * x;
无参数需保留括号:
const greet = () => console.log('Hello');
多行函数体需用大括号:
const sum = (a, b) => {const result = a + b;return result;
};
模板字符串
模板字符串使用反引号(`)定义,支持多行文本和嵌入表达式。
基本用法:
const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, Alice!
多行文本:
const message = `This is amulti-linestring.
`;
表达式嵌入:
const a = 5;
const b = 10;
console.log(`The sum is ${a + b}`); // The sum is 15
解构赋值
解构赋值可以从数组或对象中提取数据并赋值给变量。
数组解构:
const numbers = [1, 2, 3];
const [first, second, third] = numbers;
console.log(first); // 1
对象解构:
const person = { name: 'Bob', age: 30 };
const { name, age } = person;
console.log(name); // Bob
默认值:
const { name = 'Anonymous', age = 20 } = {};
console.log(name); // Anonymous
重命名:
const { name: personName, age: personAge } = person;
console.log(personName); // Bob
扩展运算符与剩余参数
扩展运算符(...
)可用于展开数组或对象,剩余参数用于收集多个参数为数组。
数组展开:
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]
对象展开:
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }
剩余参数:
function sum(...numbers) {return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3)); // 6
类与继承
ES6 引入了 class
语法,简化了原型继承的实现。
类定义:
class Person {constructor(name, age) {this.name = name;this.age = age;}greet() {console.log(`Hello, my name is ${this.name}`);}
}
继承:
class Student extends Person {constructor(name, age, grade) {super(name, age);this.grade = grade;}study() {console.log(`${this.name} is studying`);}
}
Promise 与异步
Promise
用于处理异步操作,避免回调地狱。
基本用法:
const fetchData = () => {return new Promise((resolve, reject) => {setTimeout(() => {resolve('Data fetched');}, 1000);});
};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);}
}
集合与映射
Set
和 Map
提供了新的数据结构。
Set
用法:
const uniqueNumbers = new Set([1, 2, 2, 3]);
console.log(uniqueNumbers); // Set {1, 2, 3}
Map
用法:
const map = new Map();
map.set('name', 'Alice');
map.set('age', 25);
console.log(map.get('name')); // Alice
迭代器与生成器
迭代器协议允许自定义对象的迭代行为,生成器函数简化了迭代器的创建。
迭代器:
const iterable = {[Symbol.iterator]() {let step = 0;return {next() {step++;return { value: step, done: step > 3 };}};}
};for (const value of iterable) {console.log(value); // 1, 2, 3
}
生成器:
function* generator() {yield 1;yield 2;yield 3;
}const gen = generator();
console.log(gen.next().value); // 1
代理与反射
Proxy
和 Reflect
提供了元编程能力。
Proxy
用法:
const target = {};
const handler = {get(target, prop) {return prop in target ? target[prop] : 'default';}
};const proxy = new Proxy(target, handler);
console.log(proxy.name); // default
Reflect
用法:
const obj = { a: 1 };
console.log(Reflect.get(obj, 'a')); // 1