ts 一个class类的构造函数里面无法使用extends怎么根据另一个类的实例自动继承另一个类的多个所有公有方法
可以使用接口来实现类的继承,例如:
interface AnotherClassInterface {
method1(): void;
method2(): string;
// 这里列出另一个类的所有公有方法
}
class MyClass implements AnotherClassInterface {
constructor(anotherInstance: AnotherClassInterface) {
this.method1 = anotherInstance.method1.bind(anotherInstance);
this.method2 = anotherInstance.method2.bind(anotherInstance);
// 在构造函数里面使用另一个类的实例,将所有公有方法绑定到当前实例上
}
method1: () => void;
method2: () => string;
// 实现继承的方法
}
这里通过定义一个接口 AnotherClassInterface,列出了另一个类的所有公有方法。然后在 MyClass 的构造函数中,将另一个类的实例的公有方法绑定到当前实例上,实现了类的继承
原文地址: http://www.cveoy.top/t/topic/hxHs 著作权归作者所有。请勿转载和采集!