Mixin Factories Compose Class Behavior
Mixin factories take a base class and return an extended one, stacking state and behavior along a controlled super chain instead of deep inheritance.
Code
// 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');Output
Captured from a sandboxed run of this snippet in the build pipeline.
true true
{"id":"deploy-42","touchedAt":1795233679737}
trueMixin Factories Compose Class Behavior: inside the code
The code’s whole job belongs to the classes Job and TrackedJob and the functions Timestamped and Serializable.
It builds and returns a fresh value rather than reusing its inputs.
What to watch for
- The environment needs no preparation beyond having the interpreter or compiler.
Putting it to use
The code pivots on const Timestamped = (Base)
Core lines
return { ...super.toJSON?.(), touchedAt: this.touchedAt };
const Timestamped = (Base) => class extends Base {
touchedAt = null;
touch() { this.touchedAt = Date.now(); }
};
toJSON() { return { id: this.id }; }
Interactive Tools for This Topic
Docker Run to Compose ConverterTransform docker run CLI commands with ports, environment variables, volumes, networks, and resource limits into clean compose.yaml service definitions.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does `Timestamped` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `Timestamped`, `Serializable` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.