调用函数时出错:TypeError:this.myFunction不是函数

时间:2018-02-01 14:23:17

标签: angular typescript

我有以下简化功能:

   public constructPoints() {
       mapArray.push("hello");      
    }

我从两个位置调用该功能:

 protected onDataSourceLoaded() {
    this.constructPoints();   
 }

public OnSourceChanged(source) {   
    this.pageSource = source; 
    //this.onDataSourceLoaded();
    this.constructPoints();   
}

在同一个文件中,我有一个代码块,其中引用了OnSourceChanged:

  const sourceNavContext:SourceNavContext = {
      Items: this.sourceNavItems,
      Context: this.fieldFormContext,
      onRecordChanged: this.OnSourceChanged 
    };

OnDataSourceLoaded是一个从基类继承的函数:

 protected abstract onDataSourceLoaded()

//and in that base class there's also this:


 private wireupDataLoadedSubscription() {
    let subscription
      = this.dataLoadedNotifier.subscribe(next => this.onDataSourceLoaded());
    this.subscriptions.push(subscription);
  }

这是我的问题:当我从onDataSourceLoaded调用this.constructPoints时,它就会完成它应该做的事情。当我从OnSourceChanged调用它时,我收到以下错误: TypeError:this.constructPoints不是函数

我不明白为什么我会收到此错误。有人能指出我正确的方向吗?正如您所看到的,我在最后一个代码片段中注释掉了一行,其中调用了this.onDataSourceLoaded。如果我取消注释这一行,我会得到相同的错误但是对于这个函数。

1 个答案:

答案 0 :(得分:1)

问题在于您将该功能传递给其他人并且在没有通过您期望的this参数的情况下调用它。尝试使用箭头功能捕获this

const sourceNavContext:SourceNavContext = {
       Items: this.sourceNavItems,
       Context: this.fieldFormContext,
       onRecordChanged: s => this.OnSourceChanged (s)
 };

在JavaScript中this由调用者决定,而不是由声明函数的位置决定。有关更多信息,请参阅herehere