Javascript 如何在Typescript中扩展这两个类
我需要从同一名称空间扩展这两个类 例如:Javascript 如何在Typescript中扩展这两个类,javascript,typescript,typescript2.0,typescript1.5,Javascript,Typescript,Typescript2.0,Typescript1.5,我需要从同一名称空间扩展这两个类 例如: declare namespace myNameSpace{ class class1{ ///some methods will be here } class class3 extends class1{ //some method wil be here } class class2 extends myNameSpace. class3 { //some method
declare namespace myNameSpace{
class class1{
///some methods will be here
}
class class3 extends class1{
//some method wil be here
}
class class2 extends myNameSpace. class3 {
//some methods will be here
}
export namespace class2 {
//declaration will be here
}
}
我需要扩展“myNameSpace.class1”类和“class2”命名空间
class newClass extends myNameSpace.class1, myNameSpace.class2 {
constructor() {
super();
}
}
如果我调用这两个类,我会得到一条错误消息
类只能扩展单个类
在typescript中是否有其他方法解决此问题
在typescript中是否有其他方法解决此问题
TypeScript是设计上的单一继承。您可以使用,但不能重写方法(除非您编写自定义的applyMixins
方法)
使用以下方法:
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
derivedCtor.prototype[name] = baseCtor.prototype[name];
});
});
}
你必须实施(在空路上)
现在,使用混合实际使其成为多扩展类:
applyMixins(NewClass, [myNameSpace.class1, myNameSpace.class2]);
现在您可以创建这个类了
const foo = new NewClass()
foo.methodFrom1() // actually calls nameSpace.class1.prototype.methodFrom1
您可以创建接口并在类中实现它们。请先解决可能重复的问题。副本的标题非常相似,是页面上的第一个链接。
const foo = new NewClass()
foo.methodFrom1() // actually calls nameSpace.class1.prototype.methodFrom1