TypeScript, 在其他类的内部方法中,使用this关键字,调用本类的方法,提示this.XXX is not a function

例如,本例中,在datetimepicker的on()方法中,调用本类的方法query(),无法使用this关键字。

$('#date2').datetimepicker({
      language:'zh-CN',
      format:'yyyy-mm-dd'
      //...
    }).on('change', 
    function(){
      this.query(); //无效
    }
);

query(){
   //...
}

探索了一段:时间,找到了答案:https://stackoverflow.com/questions/16157839/typescript-this-inside-a-class-method

代码改成如下写法:

changeDtp = () => {
    this.query(); //有效
}

$('#date2').datetimepicker({
      language:'zh-CN',
      format:'yyyy-mm-dd'
      //...
}).on('change', 
    this.changeDtp
);

问题解决。

Anders的原话:“The this in arrow functions is lexically scoped“

                             “this关键字在箭头方法里面管用”