【发布时间】:2019-07-03 14:50:22
【问题描述】:
我正在 Typescript 中试验一些 mixin,并且已经掌握了使用几种不同方法构建 mixin 的基础知识。在所有这些中,我都遇到了同样的错误。
这是我的 mixin 类:
export class OnDestroyMixin implements OnDestroy {
public destroyStream: Subject<void> = new Subject();
ngOnDestroy(): void {
console.log(`on destroy from mixin`);
this.destroyStream.next();
this.destroyStream.complete();
}
}
并且每当调用 on destroy 函数时(在它被混入另一个类之后)this.destroyStream 不存在所以我得到一个Cannot read property 'next' of undefined 错误。
我考虑过在构造函数中设置它,但我也不确定构造函数在 mixins 中是如何工作的......
我认为这应该是可能的。
我目前使用的mixin方法是一个mixin装饰器:
export function Mixin(baseCtors: Function[]) {
return function (derivedCtor: Function) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
const descriptor = Object.getOwnPropertyDescriptor(baseCtor.prototype, name);
if (name === 'constructor')
return;
if (descriptor && (!descriptor.writable || !descriptor.configurable || !descriptor.enumerable || descriptor.get || descriptor.set)) {
Object.defineProperty(derivedCtor.prototype, name, descriptor);
} else {
derivedCtor.prototype[name] = baseCtor.prototype[name];
}
});
});
};
}
这是我从网上某处复制的,但正如我所说,我尝试了几种不同的方法,基本上都是将属性从一个原型复制到另一个原型。
【问题讨论】:
标签: typescript mixins