简体   繁体   中英

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

I have the following simplified function:

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

I'm calling the function from two spots:

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

AND

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

In the same file, I have this code block where OnSourceChanged is referenced:

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

OnDataSourceLoaded is a function that's being inherited from a base class:

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

HERE'S MY QUESTION: When I call this.constructPoints from onDataSourceLoaded, it does what it's supposed to do. When I call it from OnSourceChanged, I get the following error: TypeError: this.constructPoints is not a function

I don't understand why I'm getting this error. Can someone point me in the right direction? As you can see, I've commented out a line in the last code snippet where this.onDataSourceLoaded is called. If I uncomment this line, I get the same error but for this function.

The problem is that you pass the function to someone else and they call it without passing you the this parameter you expect. Try using an arrow function to capture this

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

In JavaScript this is determined by the caller not by where the function is declared. See here and here for more

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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