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

前端 未结 4 1204
青春惊慌失措
青春惊慌失措 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:33

    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!");
    

提交回复
热议问题