← 中文资源

简体中文版本

mixin 工厂组合类行为

mixin 工厂接收基类并返回扩展类:Timestamped 只加状态与 touch,Serializable 复写 toJSON 并沿 super 链接到 Job,组合顺序决定行为叠加,避免深层继承。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

true true
{"id":"deploy-42","touchedAt":1795233679737}
true

实现说明

除了类 Job、TrackedJob和函数 Timestamped、Serializable,文件里再无其他定义。 返回的是新建的值,不复用入参。

常见问题

Timestamped 会修改传入的参数吗?

不会修改。入参只读,返回值是全新构造的。

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。 文件在加载时定义 Timestamped、Serializable。

入口签名:const Timestamped = (Base)

核心语句

return { ...super.toJSON?.(), touchedAt: this.touchedAt };
const Timestamped = (Base) => class extends Base {
  touchedAt = null;
  touch() { this.touchedAt = Date.now(); }
};
toJSON() { return { id: this.id }; }

代码示例

// mixin 工厂:接收基类,返回扩展后的类,按需叠加行为
const Timestamped = (Base) => class extends Base {
  touchedAt = null;
  touch() { this.touchedAt = Date.now(); }
};

const Serializable = (Base) => class extends Base {
  // super 链最终接到 Job.toJSON,再混入 mixin 自己的字段
  toJSON() {
    return { ...super.toJSON?.(), touchedAt: this.touchedAt };
  }
};

class Job {
  constructor(id) { this.id = id; }
  toJSON() { return { id: this.id }; }
}

// 组合顺序决定 super 链:Timestamped 只加状态,Serializable 复写 JSON 形状
class TrackedJob extends Timestamped(Serializable(Job)) {}

const job = new TrackedJob('deploy-42');
job.touch();
console.log(job instanceof TrackedJob, job instanceof Job);
console.log(JSON.stringify(job));
console.log(typeof job.touchedAt === 'number');