【问题标题】:Can I trigger subclass's member function from constructor of parent class in Typescript?我可以从 Typescript 中父类的构造函数触发子类的成员函数吗?
【发布时间】:2019-03-09 18:18:51
【问题描述】:
class Person {
    contructor() {
        this.someSubclassMember();
    }
}

class Student {
    contructor() {
        super();
        this.someSubclassMember.bind(this); 
    }

    someSubclassMember() {

    }
}

我知道我可以为 somSubclassMember 定义 protected,但我想从父类迭代子类原型?

这可行吗? 谢谢

PS:我在 coffeescript 中看到了它的可行性。这是coffeescript编译的代码

  module.exports = ProviderOS = (function(superClass) {
    extend(ProviderOS, superClass);

    function ProviderOS() {
      this.doInternalGetJobCollection = bind(this.doInternalGetJobCollection, this);
      this.doCreateJob = bind(this.doCreateJob, this);
      this.doCreateOnetimeJob = bind(this.doCreateOnetimeJob, this);
      this.doCreateHourlyJob = bind(this.doCreateHourlyJob, this);
      this.doCreateDailyJob = bind(this.doCreateDailyJob, this);
      this.doExecuteJob = bind(this.doExecuteJob, this);
      this.doGetServerInformation = bind(this.doGetServerInformation, this);
      this.getBaseName = bind(this.getBaseName, this);
      this.onInit = bind(this.onInit, this);
      return ProviderOS.__super__.constructor.apply(this, arguments);
    }

在这种情况下,我可以从超类访问子类成员。 但 typescript 需要在访问 this 之前调用 super。

【问题讨论】:

  • 您可以将方法声明为抽象,但在构造函数中调用它不是一个好主意。该方法将在派生类构造函数(构造函数的主体和字段初始化)之前运行,从而导致各种奇怪和意外的行为。

标签: typescript class inheritance coffeescript super


【解决方案1】:

我自己解决了。 超类有一个名为(init) 的成员函数,子类覆盖它。在这种情况下,超类做 init() 是调用子类的 init。 从子类中,我可以将其用作子类的构造函数。

【讨论】:

    猜你喜欢
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多