可以使用super关键字调用父类的构造函数,然后使用Object.assign()方法将另一个类的实例的公有方法添加到子类实例中。具体实现如下:

class Parent {
  public sayHello() {
    console.log('Hello!');
  }
}

class Child extends Parent {
  constructor(parent: Parent) {
    super();
    Object.assign(this, parent);
  }
}

const parent = new Parent();
const child = new Child(parent);
child.sayHello();  // 输出 "Hello!"

在Child类的构造函数中,首先调用父类的构造函数,然后使用Object.assign()方法将parent对象的所有公有方法添加到this对象中,从而实现继承。最后,我们可以通过child对象调用从Parent类继承来的sayHello()方法。

ts class类的构造函数里面怎么根据另一个类的实例继承另一个类的所有公有方法

原文地址: http://www.cveoy.top/t/topic/hxHb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录