Typescript: How to call method defined with arrow

2020-03-01 15:00发布

问题:

Given

class BaseClass{

  count:number=0;

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

class ChildClass extends BaseClass{
  public someMethod=():void=>{
     super.someMethod();
     //Do more work here.
  }
}

I receive the error message:

Only public methods of the base class are accessible via the 'super' keyword.

@Basarat provides some information here but this seems like a real hack to the language. typescript arrow operator to define a function on prototype

How might this be done while preserving contextual use of 'this'?

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

回答1:

For the sake of argument, assume you

  • Are using the fat-arrow syntax because the methods are being triggered by UI events or callbacks (in my case knockout click events)
  • Need inheritance to eliminate redundancy in UI (or callback) respondent code.

A minimally hackish (if not elegant) answer is to split your function into two calls that address the two issues:

Class A {
    public handleScope = () => {
        return this.handleInheritance();
    }

    public handleInheritance() {
        // do work
    }
}

Class B extends A {
    public handleInheritance() {
         super.handleInheritance() // super works here
         // additional work
    }
}

I'm the first to admit that doubling functions is "ugly", but IMHO a lot less ugly than the other options I've seen. To help standardize naming, I'm naming the one-line "scoping" function the name of the base function (e.g. myFunction) plus "Scoper" (i.e. myFunctionScoper). This is also IDE-friendly because you'll often get the Scoper method as a hinted option when you start to type the name for the inheritable method.



回答2:

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

}


回答3:

Without a function implementation in the prototype, there's no way for the derived class to 'find' the base class implementation. You can separate it out so that you have one method for preserving this and another for using via super:

class BaseClass {
  count: number = 0;

  someMethodImpl() {
    this.count++;
  }

  public someMethod = this.someMethodImpl;
}

class ChildClass extends BaseClass {
  public someMethod = (): void=> {
    super.someMethodImpl();
    //Do more work here.
  }
}


回答4:

Just would like to capture an "answer" to this question from another discussion here: https://typescript.codeplex.com/workitem/2491

Definitely not efficient in terms of memory or processing overhead but it does answer the question.

class Base {
    x = 0;
    constructor() {
        for (var p in this)
            if (!Object.prototype.hasOwnProperty.call(this, p) && typeof this[p] == 'function') {
                var method = this[p];
                this[p] = () => { method.apply(this, arguments); };
                // (make a prototype method bound to the instance)
            }
    }
}

class A extends Base {
    doSomething(value) { alert("A: " + value + " / x == " + this.x); }
}

class B extends A {
    doSomething(value) { alert("B: " + value + " / x == " + this.x ); super.doSomething(value); }
}

var b = new B();
var callback = b.doSomething;
callback("Cool!");