Skip to content

类与继承 ​

一上来就讲 OOP 的书都在讲"封装、继承、多态"——三个词背了十遍你写的类还是写不动。类在实现层根本不复杂:一个对象就是「字段哈希表 + 一个指向类的指针」,一个类就是「方法哈希表 + 一个指向父类的指针」,p.foo 这一行,实现层不过是顺着这两条链各走一遍。讲不清这层,后面 V8 的 HiddenClass / CPython 的 type_call / JVM 的 vtable 永远是黑箱。这篇用 50 行 TS 把它拆完,顺带把新手最容易翻车的 super.foo() 讲明白。

一句话先记住:对象 = 字段表 + 类指针,类 = 方法表 + 父类指针;p.foo 查找 = 先看实例字段,再沿着类指针往上爬;super.foo 不是查 this 的父类,是查"当前方法定义所在的那个类"的父类。


一、两张表 + 两个指针 ​

实现一门 OOP 语言,90% 工作量在两张哈希表。对象只放字段,类只放方法——几乎所有动态 OOP 语言的共同设计 (Python / Ruby / Lua / Mochi)。一个 Point 实例化 1000 个,方法各塞一份就爆内存——所以方法集中放在类里,对象只保留一个指向类的指针。JS 的 prototype 链本质相同,只是把"类"也写成普通对象(第四节细讲)。

二、方法查找:沿着类指针往上爬 ​

p.foo 的查找规则只剩四条:

1. 看 p.__fields__["foo"]              → 有? 返回
2. 看 p.__class__.methods["foo"]       → 有? 返回(绑定 this=p)
3. 看 p.__class__.__super__.methods    → 有? 返回
4. 一路往父类爬到 null                  → 报错 "undefined property"

这就是动态分派 (dynamic dispatch)——p.distance() 调哪个,运行时才决定 (取决于 p 当前指向的类)。静态分派 (static dispatch) 只有静态类型语言玩得起,编译期确定 p 的类型,直接生成 call Point::distance 这种固定地址的指令——Rust / C++ 的非虚函数、JVM 的 invokestatic 走这条路,飞快。Mochi 是动态语言,所有方法调用都动态分派,这也是动态语言慢的根因之一。

具体例子:

text
class Point {
  init(x, y) { this.x = x; this.y = y }
  distance() { return sqrt(this.x*this.x + this.y*this.y) }
}
class ColorPoint < Point {
  init(x, y, color) { super.init(x, y); this.color = color }
  describe() { return this.color + " point" }
}

let p = ColorPoint(3, 4, "red")
print(p.distance())   // 5
print(p.describe())   // "red point"

内存布局与查找路径:

   p (ColorPoint 实例)              ColorPoint                Point
   ┌────────────────┐               ┌──────────────┐         ┌──────────────┐
   │ __class__  ────┼──────────────→│ __super__ ───┼────────→│ __super__:nil│
   │ x: 3           │               │ init  → <fn> │         │ init  → <fn> │
   │ y: 4           │               │ describe→<fn>│         │ distance→<fn>│
   │ color: "red"   │               └──────────────┘         └──────────────┘
   └────────────────┘                     ▲                        ▲
   p.describe()  ───────── 第 1 站找到 ───┘                        │
   p.distance()  ── 第 1 站没有 ──────────── 第 2 站找到 ──────────┘

三、super 的实现:新手最容易翻车的地方 ​

ColorPoint.init 里有 super.init(x, y)。直觉反应:super 就是 this.__class__.__super__,查父类调 init 不就行?错。看这个继承链:

text
class A { greet() { return "A" } }
class B < A { greet() { return "B-" + super.greet() } }
class C < B { greet() { return "C-" + super.greet() } }

print(C().greet())   // 期望: "C-B-A"

如果 super.greet() 真的等于 this.__class__.__super__.greet:

  • C().greet():this.__class__ 是 C,super → B,跳 B.greet(),this 还是 C 实例
  • B.greet() 体内的 super.greet():this.__class__ 还是 C,super 又跳回 B,死循环!

正确实现:super.foo 不是查 this 的父类,是查"当前方法定义所在的那个类"的父类的 foo。

C().greet() 执行:
  方法定义在 C → super 绑死到 B → 调 B.greet() (this 仍是 C 实例)
      ↓
  B.greet() 体内 super.greet():
  方法定义在 B → super 绑死到 A   ← 不是 C 的父类!
                → 调 A.greet() → "A"
      ↓
  B.greet() 返回 "B-A"  → C.greet() 返回 "C-B-A"  ✓

实现层:每个方法编译时记一个隐式的 __defining_class__ 字段,super.foo 编译成「沿着 __defining_class__.__super__ 查找 foo」,完全和 this 的实际类无关。Python 3 用 __class__ cell + 编译期改写做到,JS 用 [[HomeObject]] 内部槽——核心思路一致。


四、单继承 vs 原型链:本质等价,写法不同 ​

Mochi 选单继承,JS 选原型链——表面两套设计,实现层是同一件事:

视角Mochi / PythonJavaScript
"类"是什么独立的 Class 对象一个普通对象 (prototype)
对象 → 类的指针__class____proto__ (内部槽)
类 → 父类的指针__super__prototype 对象的 __proto__
方法存在哪类对象的方法 mapprototype 对象的字段
查找规则沿 __class__ → __super__沿 __proto__ 链

JS 把"类"和"对象"合并了——没有"类对象"这个独立物种,所谓"类"就是「一个普通对象 + 几个方法当字段」。ES6 的 class 关键字只是语法糖,底下还是 prototype 链。Mochi 走 Python / Lua 这条路:类和实例是两种不同的运行时对象,更接近大多数人对"OOP"的心智。


五、最简实现:50 行 TS ​

typescript
type Value = number | string | boolean | MochiInstance | MochiFunction;

class MochiClass {
  constructor(public name: string,
              public methods: Map<string, MochiFunction>,
              public superclass: MochiClass | null) {}
  findMethod(name: string): MochiFunction | null {
    if (this.methods.has(name)) return this.methods.get(name)!;
    return this.superclass ? this.superclass.findMethod(name) : null;
  }
}

class MochiInstance {
  fields = new Map<string, Value>();
  constructor(public klass: MochiClass) {}
  get(name: string): Value {
    if (this.fields.has(name)) return this.fields.get(name)!;
    const m = this.klass.findMethod(name);
    if (m) return m.bind(this);          // 绑定 this 后返回
    throw new Error(`undefined property '${name}'`);
  }
  set(name: string, value: Value) { this.fields.set(name, value); }
}

function instantiate(klass: MochiClass, args: Value[]): MochiInstance {
  const inst = new MochiInstance(klass);
  const init = klass.findMethod("init");
  if (init) init.bind(inst).call(args);
  return inst;
}

class MochiFunction {
  // definingClass 是 super 的秘密——它告诉 super 从哪里往上找
  constructor(public body: AST, public params: string[],
              public closure: Env, public definingClass: MochiClass | null) {}
  bind(self: MochiInstance): MochiFunction { /* 把 self 塞进闭包 */ ... }
}

// super.foo 的求值:沿 definingClass.superclass 找,this 不变
function evalSuper(method: string, defining: MochiClass, self: MochiInstance) {
  const fn = defining.superclass?.findMethod(method);
  if (!fn) throw new Error(`undefined super.${method}`);
  return fn.bind(self);
}

跑得通,就是 Mochi 类机制的全部秘密。


六、工业级是怎么做的 ​

  • CPython:类和实例都塞进 PyObject 系统——type 自己也是对象 (type.__class__ == type,递归终止)。关键路径在 Objects/typeobject.c:type_call (创建实例)、_PyType_Lookup (方法查找)、super_getattro (super 实现);Objects/object.c 的 PyObject_GetAttr 是 p.foo 入口。
  • V8:不是普通哈希表——引入 HiddenClass (也叫 Map):结构相同的对象共享一个 HiddenClass,字段访问编译成「偏移量 + 类型 guard」(Inline Cache)。看 src/objects/js-objects.h 与 src/objects/map.h。
  • JVM:走 vtable 路线——每个类一张方法指针表,虚方法调用编译成「取 vtable + 偏移 + 间接跳转」,O(1) 不需要哈希查找。这是静态类型语言的红利。

七、Mochi 这里偷懒了 ​

  • 只做单继承——没有 mixin、trait、interface。要多个"行为"组合,只能 composition over inheritance。
  • 不做 MRO (Method Resolution Order):多继承要解决菱形 (A→B, A→C, D→B+C),Python 用 C3 线性化算法算出确定的查找顺序。Mochi 不碰。
  • 不做属性描述符 / __getattr__ / metaclass——这些 Python 的高级元编程留给第 19 篇。
  • 方法查找没缓存——每次都遍历父类链。V8 用 Inline Cache、CPython 用 _PyType_Lookup 内部缓存,Mochi 不做。

下一篇:17-模块系统.md,讲清楚 import "math" 这一行背后到底做了什么——模块路径解析、加载缓存、循环依赖,以及为什么 CJS 和 ESM 已经打了十年还没打完。