Mixin
JS 不支持多继承,但可以通过 Mixin 模拟。
export function mix<T extends new (...args: any[]) => unknown>(ctor: T, ...bases: any[]) {
bases.forEach((baseCtor) => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
Object.defineProperty(
ctor.prototype,
name,
Object.getOwnPropertyDescriptor(baseCtor.prototype, name) || Object.create(null)
)
})
})
return ctor
}
class A {
a() {console.log('a')}
}
class B {
b() {console.log('b')}
}
class C {}
mix(C, A, B)
interface C extends A, B {}
const c = new C()
c.a() // a
c.b() // b
最后更新于