TypeScript 继承实现:无extends关键字继承父类方法
TypeScript 继承实现:无extends关键字继承父类方法
在 TypeScript 中,如果不能使用 extends 关键字,如何实现继承并保留子类方法呢?例如,以下代码中,子类 Child 继承了父类 Parent 的方法,但由于 extends 被禁用,methodC 方法丢失了。
class Parent {
constructor() {}
public methodA() {}
public methodB() {}
}
const parent = new Parent();
class Child {
constructor() {
Object.setPrototypeOf(this, Object.getPrototypeOf(parent));
}
public methodC() {}
}
const child = new Child();
child.methodA();
child.methodB();
child.methodC();
为了实现继承并保留 methodC 方法,可以使用 Object.assign() 方法来继承父类的方法。
class Parent {
constructor() {}
public methodA() {}
public methodB() {}
}
const parent = new Parent();
class Child {
constructor() {
Object.assign(this, parent);
}
public methodC() {}
}
const child = new Child();
child.methodA();
child.methodB();
child.methodC();
在 Child 类的构造函数中,使用 Object.assign() 方法将父类的方法复制到子类实例上,这样子类就能继承父类的方法。这样就可以保留 methodC 方法并且能够调用父类的 methodA 和 methodB 方法。
注意:
Object.assign() 方法只是将父类的方法复制到子类实例上,并不真正实现继承。也就是说,子类没有继承父类的原型链,因此不能访问父类的私有成员和 protected 成员。如果需要访问父类的私有成员或 protected 成员,仍然需要使用 extends 关键字实现继承。
原文地址: https://www.cveoy.top/t/topic/o0EC 著作权归作者所有。请勿转载和采集!