Published
Edited
Aug 5, 2020
Insert cell
md`# Mixin 模式的实现`
Insert cell
md`将多个类的接口“混入”(mix in)另一个类。`
Insert cell
function copyProperties(target, source) {
for (let key of Reflect.ownKeys(source)) {
if ( key !== 'constructor'
&& key !== 'prototype'
&& key !== 'name'
) {
let desc = Object.getOwnPropertyDescriptor(source, key);
Object.defineProperty(target, key, desc);
}
}
}
Insert cell
function mix(...mixins) {
class Mix {
constructor() {
for (let mixin of mixins) {
copyProperties(this, new mixin()); // 拷贝实例属性
}
}
}
for (let mixin of mixins) {
copyProperties(Mix, mixin); // 拷贝静态属性
copyProperties(Mix.prototype, mixin.prototype); // 拷贝原型属性
}
return Mix;
}
Insert cell
md`上面代码的mix函数,可以将多个对象合成为一个类。使用的时候,只要继承这个类即可。`
Insert cell
class Loggable{
}
Insert cell
class Serializable{}
Insert cell

class DistributedEdit extends mix(Loggable, Serializable) {
// ...
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more