Search code examples
typescriptclassinheritancecoffeescriptsuper

Can I trigger subclass's member function from constructor of parent class in Typescript?


class Person {
    contructor() {
        this.someSubclassMember();
    }
}

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

    someSubclassMember() {

    }
}

I know I can define protected for somSubclassMember but I would like to iterate over subclasses prototype from parent class?

Is this feasible? Thank you

PS: I saw its feasible in coffeescript. Here's the coffeescript compiled code

  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);
    }

In this case, I can access subclass member from super class. But typescript required to call super before accessing this.


Solution

  • I solved it myself. The superclass has a member function called(init) and subclass overrides it. In this case, superclass do init() is to call init of subclass. From subclass, I can use it as a constructor of subclass.