是否可以从现有实例继承?
特定用例:我有一个自定义EventEmitter类,它可以生成子发射器。子发射器也是EventEmitter,它们只是在整个链中发射。
// _EventEmitter is a standard EventEmitter
class EventEmitter extends _EventEmitter {
public parent?: EventEmitter;
public emit(event: string | symbol, ...args: any[]): boolean {
const result = super.emit(event, ...args);
if (this.parent) {
this.parent.emit(event, ...args);
}
return result;
}
public subemitter() {
const emitter = new EventEmitter();
emitter.parent = this;
return emitter;
}
}
我想声明X的所有实例都继承自特定的静态EventEmitter。
在这种情况下,所有段落都将其事件发送到集中的汇总发射器。
class Paragraph extends EventEmitter {
public static emitter = new EventEmitter();
constructor() {
super();
// Obviously this will work, but this is breaking abstraction
this.parent = Paragraph.emitter;
// Alternatively, i could allow the following:
// super(Paragraph.emitter)
// by allowing super(parent?: EventEmitter)
// Would like to apply constructor to Paragraph.emitter.subemitter().
// ... Initialize other methods ...
}
}
逻辑上,可以使用原型链创建对象,如下所示:
此->段落->事件发射器。
唯一的问题是,是否有一种优雅的方法可以做到这一点。