章节目录 · 8 章
JavaScript 教程 · 第 6 章
ES6+:类、模块、Symbol、生成器
2015 年之后 JavaScript 每年都发布新版本,带来了箭头函数、解构、类、模块、Promise、可选链等大量现代语法。如今的生产项目基本都建立在这套语法之上。本章重点讲:
- class 的完整用法(继承、私有字段、静态方法)
- ES 模块的导入导出各种写法
- Symbol:独一无二的值
- 生成器 Generator:可以暂停的函数
- Promise 补充(完整内容下一章)
一、class:原型继承的语法糖
ES6 的 class 语法本质上是原型继承的糖,让代码组织更清晰、更符合传统 OOP 的阅读习惯。它没有引入新的继承模型,底层还是原型链。
基本结构
class User {
// 构造函数:new User(...) 时调用
constructor(name, level = 1) {
this.name = name;
this.level = level;
this.createdAt = new Date();
}
// 实例方法(自动放在 User.prototype 上)
greet() {
return `我是 ${this.name},等级 ${this.level}`;
}
// getter:访问时像属性,实际是方法
get title() {
return `${this.name}(Lv.${this.level})`;
}
// setter:赋值时触发
set level(v) {
if (v < 1 || v > 100) throw new RangeError("等级必须在 1~100");
this._level = v;
}
// 静态方法(挂在 User 类本身,不在实例上)
static fromPlain(obj) {
const u = new User(obj.name, obj.level);
return u;
}
// 静态属性
static MAX_LEVEL = 100;
}
const u1 = new User("黄帝", 5);
console.log(u1.greet()); // 我是 黄帝,等级 5
console.log(u1.title); // 黄帝(Lv.5)
const plain = { name: "小明", level: 3 };
const u2 = User.fromPlain(plain); // 静态方法不需要实例
console.log(User.MAX_LEVEL); // 100
getter / setter 的妙用
class Temperature {
constructor(celsius) {
this._celsius = celsius;
}
get celsius() {
return this._celsius;
}
set celsius(v) {
this._celsius = v;
}
// getter 可以派生出新值,setter 可以拆分存入多个属性
get fahrenheit() {
return this._celsius * 9 / 5 + 32;
}
set fahrenheit(f) {
this._celsius = (f - 32) * 5 / 9;
}
}
const t = new Temperature(25);
console.log(t.fahrenheit); // 77 ← 25°C = 77°F
t.fahrenheit = 68;
console.log(t.celsius); // 20 ← 68°F = 20°C
// 也可以用来做校验
class Square {
constructor(side) { this.side = side; }
get area() { return this.side ** 2; }
set side(v) {
if (v <= 0) throw new Error("边长必须大于 0");
this._side = v;
}
}
私有字段(ES2022)
以 # 开头的字段是真正的私有,类外部无法访问:
class BankAccount {
#balance = 0; // 私有字段,声明时直接赋值
#pin;
constructor(initialBalance, pin) {
this.#balance = initialBalance;
this.#pin = pin;
}
deposit(amount) {
if (amount > 0) this.#balance += amount;
}
withdraw(amount, pin) {
if (pin !== this.#pin) throw new Error("密码错误");
if (amount <= 0 || amount > this.#balance) throw new Error("金额无效");
this.#balance -= amount;
}
getBalance() {
return this.#balance;
}
}
const acc = new BankAccount(1000, "1234");
acc.deposit(500);
acc.withdraw(200, "1234");
console.log(acc.getBalance()); // 1300
// console.log(acc.#balance); // ❌ SyntaxError: Private field '#balance' must be declared in an enclosing class
// acc.#balance = 99999; // ❌ 同样报错,无法外部访问
继承 extends / super
// 父类
class User {
constructor(name, level = 1) {
this.name = name;
this.level = level;
}
greet() {
return `我是 ${this.name},等级 ${this.level}`;
}
}
// 子类继承父类
class Admin extends User {
constructor(name, level, permissions = []) {
super(name, level); // ✅ 必须先调 super!等价于 super.constructor(name, level)
this.permissions = permissions;
}
// 覆盖父类方法
greet() {
return `[管理员] ${super.greet()}`; // super.xxx 调父类的方法
}
hasPermission(action) {
return this.permissions.includes(action);
}
// 也可以覆盖静态方法
static fromPlain(obj) {
// 先调父类的 fromPlain,再加上 Admin 特有的字段
const u = super.fromPlain(obj);
u.permissions = obj.permissions || [];
return u;
}
}
const admin = new Admin("超级管理员", 10, ["post", "delete", "users"]);
console.log(admin.greet()); // [管理员] 我是 超级管理员,等级 10
admin.hasPermission("delete"); // true
// instanceof 检查继承链
console.log(admin instanceof Admin); // true
console.log(admin instanceof User); // true ← 继承链上的所有类
console.log(admin instanceof Object); // true
console.log(admin instanceof Array); // false
// 继承链:Admin.prototype → User.prototype → Object.prototype → null
console.log(Object.getPrototypeOf(Admin.prototype) === User.prototype); // true
继承中 super 的规则
class B extends A {
constructor() {
// this.xxx = ... ← ❌ 在 super() 之前用 this 会报错
super(); // ✅ 必须第一句
this.xxx = ...; // ✅ super 之后才可以
}
method() {
// 在普通方法里,this 已经存在,可以直接调 super.xxx
super.someMethod(); // ✅
}
}
一个常见坑:class 没有提升
new User(); // ❌ ReferenceError: Cannot access 'User' before initialization
class User {}
// 对比:函数声明有提升,可以在声明前调用
greet(); // ✅
function greet() {}
class 声明存在"暂时性死区"(TDZ),从声明开始到声明结束之间都不能访问它。
二、ES 模块(import / export)
每个文件就是一个模块。ES 模块让代码可以安全地拆分、组合、复用。
命名导出与导入
// math.js
export function add(a, b) { return a + b; }
export function sub(a, b) { return a - b; }
export const PI = 3.14159;
// 也可以先声明,后 export
function multiply(a, b) { return a * b; }
export { multiply };
// 还能在 export 时起别名
export { multiply as mul };
// main.js
import { add, sub, PI } from "./math.js";
import { add as plus } from "./math.js"; // 起别名避免冲突
console.log(add(1, 2), PI); // 3 3.14159
默认导出
一个模块最多一个 default,导入时名字可以任意起:
// User.js
export default class User {
constructor(name) { this.name = name; }
}
import UserClass from "./User.js"; // 名字随便起
import { default as User } from "./User.js"; // 等价写法
const u = new UserClass("黄帝");
混合导出 + 整体导入
// config.js
export default function init() { /* ... */ }
export const VERSION = "1.0";
export function debug() { /* ... */ }
// main.js
import init, { VERSION, debug } from "./config.js"; // 同时导入默认和命名
import * as config from "./config.js"; // 整个模块当命名空间
config.default(); // 默认导出挂在 default 上
config.VERSION;
重导出(把别的模块的东西转出去)
// index.js 作为"桶文件"(barrel file),重新导出
export { add, sub } from "./math.js";
export default User, { isAdmin } from "./User.js";
// 这样外部只需要 import { add, User } from "./index.js"
// 不用分别找 math.js 和 User.js
动态导入
有些模块不需要一开始就加载,可以按需动态导入:
// 静态导入:启动时就加载
import { Editor } from "./editor.js";
// 动态导入:点击某个按钮时才加载
button.addEventListener("click", async () => {
const { Editor } = await import("./editor.js");
new Editor();
});
// 动态导入可以用变量路径
const lang = "zh-CN";
const strings = await import(`./i18n/${lang}.js`);
浏览器 vs Node.js 启用方式
| 环境 | 启用 ES 模块 | 注意 |
|---|---|---|
| 浏览器 | <script type="module" src="app.js"></script> |
自动 defer,自动启用严格模式 |
| Node.js | package.json 加 "type": "module" |
或文件后缀 .mjs |
<!-- 浏览器 -->
<script type="module">
import { add } from "./math.js";
console.log(add(1, 2));
</script>
// package.json (Node.js)
{
"type": "module",
"scripts": { "start": "node app.js" }
}
模块 vs 全局变量
每个模块文件有自己的顶层作用域,顶层声明的变量不会挂到 window(浏览器)或 global(Node)上:
// a.js
const x = 1; // 只在 a.js 模块内可见
export { x };
// b.js
const x = 2; // 和 a.js 里的 x 互不干扰
import { x as xA } from "./a.js";
console.log(x, xA); // 2 1
三、Symbol:独一无二的值
Symbol 创建的每个值都永不相等,适合做对象的"隐藏键名"或"内置行为标记":
// 创建 Symbol(description 只是帮助调试的标签,不参与相等比较)
const sym1 = Symbol("id");
const sym2 = Symbol("id");
console.log(sym1 === sym2); // false ← 描述相同也不相等
// 全局 Symbol 注册表(相同 key 会返回同一个)
const gs1 = Symbol.for("key");
const gs2 = Symbol.for("key");
console.log(gs1 === gs2); // true ← 同一个
// 作为对象键名
const obj = {};
obj[Symbol("hidden")] = "秘密";
console.log(obj); // {} ← Object.keys / for-in 看不到!
// 但直接访问 obj[那个 Symbol] 还是能拿到
// 内置 Symbol:改变原型行为
const arr = [1, 2, 3];
console.log(arr[Symbol.iterator]); // [Function: values]
// 可以给自定义对象指定 for-of 行为
const range = {
start: 1,
end: 3,
[Symbol.iterator]() {
let v = this.start;
return { next: () => v <= this.end ? { value: v++, done: false } : { done: true } };
}
};
console.log([...range]); // [1, 2, 3]
常见内置 Symbol
| Symbol | 作用 |
|---|---|
Symbol.iterator |
对象实现后可被 for...of 遍历 |
Symbol.asyncIterator |
异步可迭代(for-await-of) |
Symbol.toPrimitive |
对象转原始值时的行为 |
Symbol.toStringTag |
Object.prototype.toString.call 返回的标签 |
四、生成器 Generator:可以暂停的函数
生成器函数用 function* 声明,调用后返回一个迭代器,每次 next() 会在 yield 处暂停:
// 定义
function* idGenerator() {
let id = 1;
while (true) {
yield id++;
}
}
// 使用
const gen = idGenerator();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
// 永远不会 done(因为 while true)
// 有限次 yield
function* range(from, to) {
for (let i = from; i <= to; i++) {
yield i;
}
}
const r = range(1, 3);
console.log(r.next()); // { value: 1, done: false }
console.log(r.next()); // { value: 2, done: false }
console.log(r.next()); // { value: 3, done: false }
console.log(r.next()); // { value: undefined, done: true } ← 完成
// 因为生成器实现了迭代器协议,可以直接用 for...of
for (const n of range(1, 5)) {
console.log(n); // 1 2 3 4 5
}
console.log([...range(1, 5)]); // [1, 2, 3, 4, 5]
yield 可以接收值
function* demo() {
const a = yield "请输入第一个值";
console.log("收到 a:", a);
const b = yield "请输入第二个值";
console.log("收到 b:", b);
return a + b;
}
const d = demo();
console.log(d.next()); // { value: "请输入第一个值", done: false }
console.log(d.next(10)); // 收到 a: 10
// { value: "请输入第二个值", done: false }
console.log(d.next(20)); // 收到 b: 20
// { value: 30, done: true }
实战:异步流程控制(async/await 的前身)
Promise 出现前,生成器 + Promise 是写"同步风格异步代码"的标准套路:
// 伪代码(需要 runner 配合)
function* main() {
const user = yield fetchUser(); // 看起来像同步
const posts = yield fetchPosts(user.id);
console.log(posts);
}
// 今天用 async/await 就行,生成器更多用来做自定义迭代器
yield*:委托给另一个生成器
function* inner() {
yield "a";
yield "b";
}
function* outer() {
yield "start";
yield* inner(); // 把 inner 的所有 yield 委托过来
yield "end";
}
console.log([...outer()]); // ["start", "a", "b", "end"]
五、Proxy:代理对象的所有操作
Proxy 可以在不修改原对象的前提下,拦截对它的所有访问、修改、删除等操作。Vue 3 的响应式系统就是基于 Proxy 实现的。
const original = { name: "黄帝", level: 1 };
// handler 里可以拦截各种操作
const proxy = new Proxy(original, {
get(target, prop) {
// 访问属性时拦截
console.log(`有人访问了 ${prop}`);
return target[prop];
},
set(target, prop, value) {
// 修改属性时拦截
if (prop === "level" && (value < 1 || value > 100)) {
throw new RangeError("等级超出范围");
}
console.log(`有人把 ${prop} 改成了 ${value}`);
target[prop] = value;
return true; // 表示成功
},
has(target, prop) {
// in 操作符拦截
console.log(`检查 ${prop} 是否存在`);
return prop in target;
},
deleteProperty(target, prop) {
// delete 操作拦截
console.log(`有人删除 ${prop}`);
return delete target[prop];
}
});
proxy.level = 5; // 拦截:有人把 level 改成了 5
proxy.name; // 拦截:有人访问了 name
console.log("level" in proxy); // 拦截 + true
实用场景
// 场景 1:给对象加默认值(属性不存在时返回 0 而不是 undefined)
const counter = new Proxy({}, {
get(target, prop) {
return prop in target ? target[prop] : 0;
}
});
counter.apple = 3;
console.log(counter.apple); // 3
console.log(counter.banana); // 0 ← 自动给默认值
// 场景 2:数组下标负数索引
const arr = new Proxy([1, 2, 3, 4, 5], {
get(target, prop) {
const index = Number(prop);
if (!isNaN(index) && index < 0) {
return target[target.length + index];
}
return target[prop];
}
});
console.log(arr[-1]); // 5 ← Python 风格
console.log(arr[-2]); // 4
// 场景 3:日志记录
function withLog(obj) {
return new Proxy(obj, {
get(target, prop) {
const v = target[prop];
if (typeof v === "function") {
return function (...args) {
console.log(`调用 ${prop}`, args);
return v.apply(this, args);
};
}
return v;
}
});
}
六、练习
第 1 题:继承体系 Animal → Dog → GuideDog
任务描述:实现一个三层继承体系:
Animal(父类):构造函数接收name和age,有speak()方法返回"我是一只动物",有infogetter 返回"name(age 岁)"。Dog(继承 Animal):新增breed字段(品种),重写speak()返回"汪汪!我是一只 {breed},叫 {name}"。GuideDog(继承 Dog):新增owner字段(主人名字),重写speak()返回"工作中!正在引导主人 {owner}",额外有一个guide()方法返回"正在带 {owner} 前进..."。
💡 提示:
- 子类 constructor 里必须先调
super(name, age),否则会报 ReferenceError。- 重写方法时,子类可以选择调
super.speak()拼接,也可以完全重写。- GuideDog 继承 Dog,所以
super指的是 Dog 的 prototype,自动继承 Animal 的属性。
参考答案:
// 父类
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
speak() {
return "我是一只动物";
}
get info() {
return `${this.name}(${this.age} 岁)`;
}
}
// 中间类 Dog
class Dog extends Animal {
constructor(name, age, breed) {
super(name, age); // 调 Animal 的 constructor
this.breed = breed;
}
speak() {
return `汪汪!我是一只 ${this.breed},叫 ${this.name}`;
}
}
// 最终类 GuideDog
class GuideDog extends Dog {
constructor(name, age, breed, owner) {
super(name, age, breed); // 调 Dog 的 constructor
this.owner = owner;
}
speak() {
return `工作中!正在引导主人 ${this.owner}`;
}
guide() {
return `正在带 ${this.owner} 前进...`;
}
}
// 测试
const animal = new Animal("小黄", 3);
console.log(animal.speak()); // "我是一只动物"
console.log(animal.info); // "小黄(3 岁)"
const dog = new Dog("旺财", 5, "柴犬");
console.log(dog.speak()); // "汪汪!我是一只 柴犬,叫 旺财"
console.log(dog instanceof Animal); // true
const guide = new GuideDog("豆豆", 7, "金毛", "李大爷");
console.log(guide.speak()); // "工作中!正在引导主人 李大爷"
console.log(guide.guide()); // "正在带 李大爷 前进..."
console.log(guide.info); // "豆豆(7 岁)" ← 继承自 Animal 的 getter
第 2 题:ES 模块导入导出实战
任务描述:新建三个文件,实现一个简洁的工具模块体系:
utils.js— 命名导出sum(a, b)、capitalize(str),默认导出一个Logger类(有log(msg)、warn(msg)方法)。helpers.js— 只做"桶文件",用重导出把utils.js的所有内容转出去。main.js— 从helpers.js同时导入默认的Logger和命名的sum、capitalize,使用它们。
💡 提示:
- 默认导出用
export default X,命名导出用export { foo, bar }或export function foo(){}。- 桶文件用
export { default as Logger, sum, capitalize } from "./utils.js"语法,把默认导出也转成命名导出。- 或者用混合写法:
export default X, { a, b } from "./mod.js"。
参考答案:
// ===== utils.js =====
export function sum(a, b) {
return a + b;
}
export function capitalize(str) {
if (!str) return str;
return str[0].toUpperCase() + str.slice(1);
}
export default class Logger {
constructor(prefix = "[APP]") {
this.prefix = prefix;
}
log(msg) {
console.log(`${this.prefix} ${msg}`);
}
warn(msg) {
console.warn(`${this.prefix} ⚠️ ${msg}`);
}
}
// ===== helpers.js(桶文件)=====
// 把 utils.js 的内容全部转出去
export { default as Logger, sum, capitalize } from "./utils.js";
// ===== main.js =====
import { Logger, sum, capitalize } from "./helpers.js";
const logger = new Logger();
logger.log("程序启动");
console.log(sum(3, 4)); // 7
console.log(capitalize("hello")); // "Hello"
logger.warn("内存占用较高");
第 3 题:生成器实现斐波那契数列
任务描述:写一个生成器函数 fibonacci(),无限生成斐波那契数列(1, 1, 2, 3, 5, 8, 13...),然后用 for...of 打印前 10 项。再额外实现一个带参数的 take(iterable, n) 工具函数,从任意可迭代对象里取前 n 项。
💡 提示:
- 斐波那契的递推是:
a = 1, b = 1,每次yield a后,[a, b] = [b, a + b]。take里用break退出循环即可,不需要手动管return。
参考答案:
// 无限斐波那契生成器
function* fibonacci() {
let [a, b] = [1, 1];
while (true) {
yield a;
[a, b] = [b, a + b]; // 解构赋值交换并计算下一个
}
}
// 从可迭代对象里取前 n 项
function take(iterable, n) {
const result = [];
for (const item of iterable) {
if (result.length >= n) break;
result.push(item);
}
return result;
}
// 打印前 10 项
for (const n of take(fibonacci(), 10)) {
console.log(n);
}
// 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
// 也可以直接展开
console.log([...take(fibonacci(), 10)]);
// [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
第 4 题:Proxy 实现默认值代理 + 数组负数索引
任务描述:用 Proxy 实现两个小工具:
withDefault(obj, defaultValue)— 访问obj上不存在的属性时,返回defaultValue而不是undefined。negativeIndex(arr)— 给数组加 Python 风格的负数索引,arr[-1]取最后一个元素,arr[-2]取倒数第二个。
💡 提示:
- 在
get拦截器里判断prop in target,如果不存在就返回你要的默认值。- 负数索引里,把
prop转成数字,判断是否小于 0,是的话算成target.length + Number(prop)。- 记得处理数组的特殊属性(
length、push等方法不能被你的负数索引逻辑干扰)。
参考答案:
// 工具 1:默认值代理
function withDefault(obj, defaultValue) {
return new Proxy(obj, {
get(target, prop, receiver) {
// hasOwn 避免沿原型链找
if (!Object.prototype.hasOwnProperty.call(target, prop)) {
return defaultValue;
}
// 用 Reflect.get 保证正确的原型链行为
return Reflect.get(target, prop, receiver);
}
});
}
// 测试 withDefault
const config = withDefault({ port: 3000, host: "localhost" }, "N/A");
console.log(config.port); // 3000
console.log(config.host); // "localhost"
console.log(config.https); // "N/A" ← 不存在的属性返回默认值
console.log(config.db); // "N/A"
// 工具 2:Python 风格数组负数索引
function negativeIndex(arr) {
return new Proxy(arr, {
get(target, prop, receiver) {
// 只对整数类型的属性名做负数处理
const index = Number(prop);
if (!Number.isNaN(index) && !Number.isInteger(prop) === false && index < 0) {
// 计算真实下标
const realIndex = target.length + index;
return Reflect.get(target, String(realIndex), receiver);
}
return Reflect.get(target, prop, receiver);
}
});
}
// 测试 negativeIndex
const nums = negativeIndex([10, 20, 30, 40, 50]);
console.log(nums[0]); // 10
console.log(nums[-1]); // 50 ← 最后一个
console.log(nums[-2]); // 40 ← 倒数第二个
console.log(nums.length); // 5 ← 正常属性不受影响
第 5 题:Symbol 私有键 + class extends 中 super 规则
任务描述:
- 用
Symbol实现一个"伪私有"的计数器类Counter:每次调increment()内部计数 +1,getValue()返回当前值。外部直接访问counter时拿不到内部计数,遍历Object.keys(counter)也看不到。 - 解释(并用代码验证):为什么 ES6 class 的 constructor 里
this.xxx = 1必须放在super()之后?如果写在前面会报什么错?用一段代码演示。
💡 提示:
- 第 1 题:创建一个
const _count = Symbol("count"),在构造函数里用this[_count] = 0初始化。Object.keys和for...in默认忽略 Symbol 键,所以外部遍历不到。- 第 2 题:记住 class 继承里的 super 规则——子类 constructor 里,JavaScript 不会自动创建
this,必须等super()返回父类的实例后,this才存在。所以在super()之前用this会触发ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor。
参考答案:
// ===== 第 1 题:Symbol 伪私有计数器 =====
const _count = Symbol("internal count");
class Counter {
constructor() {
this[_count] = 0; // 用 Symbol 做键
}
increment() {
this[_count]++;
}
getValue() {
return this[_count];
}
}
const c = new Counter();
c.increment();
c.increment();
c.increment();
console.log(c.getValue()); // 3
console.log(Object.keys(c)); // [] ← Symbol 键遍历不到
console.log(Object.getOwnPropertyNames(c)); // [] ← 同样拿不到
// 但不是绝对安全:如果有人拿到了那个 Symbol 引用还是能访问
// 不过把 Symbol 定义在模块内不 export,外部就拿不到
console.log(c[_count]); // 3 ← 模块内部可以访问
// ===== 第 2 题:super 规则演示 =====
class A {
constructor() {
this.a = 1;
}
}
// ❌ 错误示范:在 super() 之前访问 this
class Bad extends A {
constructor() {
// this.b = 2; // 如果写这行会直接报错:
// ReferenceError: Must call super constructor in derived class
// before accessing 'this' or returning from derived constructor
super();
// this.b = 2; // 这里才允许 ✅
}
}
// ✅ 正确示范
class Good extends A {
constructor() {
super(); // 先调 super
this.b = 2; // super 之后才初始化自己的字段
}
}
const g = new Good();
console.log(g.a, g.b); // 1 2
为什么? 因为 ES6 class 的继承模型是:父类创建实例(this),子类在父类实例上扩展。不像 ES5 的寄生组合式继承那样子类 this = Object.create(Parent.prototype) 自己先造一个空对象。所以子类的 this 必须等父类构造完才能"接管"。
第 6 题(综合实战):构建一个可迭代的 Range + 惰性评估 pipeline
任务描述:结合本章所有知识点,构建一个 pipeline 模式 的可迭代数值序列类,支持链式调用:
const result = Seq.range(1, 100) // 1, 2, 3, ..., 100
.filter(n => n % 2 === 0) // 偶数
.map(n => n * n) // 平方
.take(10) // 取前 10 项
.toArray(); // 转成数组
console.log(result);
// [4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
💡 提示:
- 核心是
Seq类,构造函数接收一个迭代器(生成器返回的就是迭代器)。filter、map返回新的Seq实例,内部创建一个新的生成器包装原迭代器,实现惰性评估(不会提前把所有值塞进数组)。take用break提前停止迭代。toArray用[...this]把可迭代对象展开成数组。- 在
Seq类里实现[Symbol.iterator]()让它可迭代。Seq.range是一个静态工厂方法,内部用生成器产生整数序列。
参考答案:
class Seq {
constructor(iterable) {
// 接受任意可迭代对象(数组、生成器、Map、Set...)
this[Symbol.iterator] = () => iterable[Symbol.iterator]();
}
// 静态工厂:创建整数序列
static range(start, end, step = 1) {
function* gen() {
for (let i = start; step > 0 ? i <= end : i >= end; i += step) {
yield i;
}
}
return new Seq(gen());
}
// 链式 filter
filter(pred) {
const self = this;
function* gen() {
for (const item of self) {
if (pred(item)) yield item;
}
}
return new Seq(gen());
}
// 链式 map
map(fn) {
const self = this;
function* gen() {
for (const item of self) {
yield fn(item);
}
}
return new Seq(gen());
}
// 取前 n 项(惰性)
take(n) {
const self = this;
function* gen() {
let count = 0;
for (const item of self) {
if (count >= n) break;
yield item;
count++;
}
}
return new Seq(gen());
}
// 跳过前 n 项
skip(n) {
const self = this;
function* gen() {
let count = 0;
for (const item of self) {
if (count >= n) yield item;
count++;
}
}
return new Seq(gen());
}
// 转成数组(触发实际计算)
toArray() {
return [...this];
}
// reduce(归约)
reduce(fn, initial) {
let acc = initial;
for (const item of this) {
acc = fn(acc, item);
}
return acc;
}
}
// ===== 测试 =====
// 题目要求的例子
const result = Seq.range(1, 100)
.filter(n => n % 2 === 0)
.map(n => n * n)
.take(10)
.toArray();
console.log(result);
// [4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
// 另一个测试:求 1~100 奇数之和
const sum = Seq.range(1, 100)
.filter(n => n % 2 === 1)
.reduce((acc, n) => acc + n, 0);
console.log(sum); // 2500(1 + 3 + 5 + ... + 99 = 2500)
// 惰性验证:range(1, Infinity) 不会爆栈,因为是惰性的
// 只要你不 toArray(),它不会真的生成无限多的数
const lazy = Seq.range(1, Infinity).map(n => n * 2).take(5);
console.log(lazy.toArray()); // [2, 4, 6, 8, 10]
小结
- class 是原型继承的语法糖,支持 constructor、方法、getter/setter、static、extends、super、私有字段
#。 - class 有暂时性死区,不能在声明前访问(和函数声明不同)。
- ES 模块:每个文件就是模块,自动严格模式;
export/import;支持默认导出、命名导出、混合导出、重导出、动态导入。 - Symbol 创建的值永不相等,适合做隐藏属性;内置 Symbol(iterator、asyncIterator)改变原型行为。
- 生成器(
function*)可以暂停执行,yield停、next()继续;实现了迭代器协议,可以直接for...of。 - Proxy 拦截对对象的所有操作(get/set/has/delete...),Vue 3 响应式、默认值、校验、日志都是它的用武之地。
更多JavaScript教程:https://hc8.top/html-js/index.html