繁体   English   中英

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

[英]Getting error when calling function: TypeError: this.myFunction is not a function

我具有以下简化功能:

   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被调用。 如果我取消注释此行,则会得到相同的错误,但要使用此功能。

问题是您将函数传递给其他人,并且他们在未向您传递期望的this参数的情况下调用了this函数。 尝试使用箭头功能捕获this

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

在JavaScript中, this是由调用方而不是函数的声明位置确定的。 在这里这里看到更多

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM