有没有办法在接口中默认实现方法?不幸的是,我无法在基类中实现它。我觉得这是一个非常简单的问题,但在很长一段时间内找不到正确的解决方案。
/edit 在我的例子中,我需要这样的东西:
class A {
somePropertyA;
someFunctionA() {
console.log(this.somePropertyA);
}
}
class B {
somePropertyB;
someFunctionB() {
console.log(this.somePropertyB);
}
}
class C {
// Here we want to have someFunctionA() and someFunctionB()
// without duplicating code of this implementation.
}
Run Code Online (Sandbox Code Playgroud)
B entends A 和 C extends B 的解决方案对我来说并不是那么理想。
jca*_*alz 10
不。接口在运行时不存在,因此无法添加运行时代码,例如方法实现。如果您发布有关您的用例的更多细节,则可能会提供更具体或有用的答案。
编辑:
啊,您想要多重继承,而 JavaScript 中的类无法做到这一点。您可能正在寻找的解决方案是mixins。
改编手册中的示例:
class A {
somePropertyA: number;
someFunctionA() {
console.log(this.somePropertyA);
}
}
class B {
somePropertyB: string;
someFunctionB() {
console.log(this.somePropertyB);
}
}
interface C extends A, B {}
class C {
// initialize properties we care about
somePropertyA: number = 0;
somePropertyB: string = 'a';
}
applyMixins(C, [A, B]);
const c = new C();
c.someFunctionA(); // works
c.someFunctionB(); // works
// keep this in a library somewhere
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
derivedCtor.prototype[name] = baseCtor.prototype[name];
});
});
}
Run Code Online (Sandbox Code Playgroud)
那应该对你有用。也许最终这可以用装饰器来完成,但现在上面或类似的东西可能是你最好的选择。
归档时间: |
|
查看次数: |
8780 次 |
最近记录: |