Typescript: How to call method defined with arrow function in base class using super keyword in child class?

前端 未结 4 1230
青春惊慌失措
青春惊慌失措 2021-01-04 12:56

Given

class BaseClass{

  count:number=0;

  public someMethod=():void =>{
      this.count++;
  }
}

class ChildClass extends BaseClass{
  public someMe         


        
4条回答
  •  梦谈多话
    2021-01-04 13:27

    arrow functions properly or should they really only be used as a method of declaring something like a callback?

    They should really only be used for callbacks. If you want a class hierarchy then use the prototype. prototype also saves you memory.

    Forced fix: there is only one this and it is the current instance. If you overwrite this.foo in the child class the base instances this.foo is lost. Preserve the base version in the constructor

    class BaseClass{
    
      count:number=0;
    
      public someMethod=():void =>{
          this.count++;
      }
    }
    
    class ChildClass extends BaseClass{
    
      constructor(){      
          super();
          var baseSomeMethod = this.someMethod;
          this.someMethod = ()=>{
              // implement here 
          }
      }
    
    }
    

提交回复
热议问题