[英]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: 在同一文件中,我有以下代码块,其中引用了OnSourceChanged:
const sourceNavContext:SourceNavContext = {
Items: this.sourceNavItems,
Context: this.fieldFormContext,
onRecordChanged: this.OnSourceChanged
};
OnDataSourceLoaded is a function that's being inherited from a base class: 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);
}
HERE'S MY QUESTION: When I call this.constructPoints from onDataSourceLoaded, it does what it's supposed to do. 这是我的问题:当我从onDataSourceLoaded调用this.constructPoints时,它会执行应做的事情。 When I call it from OnSourceChanged, I get the following error: TypeError: this.constructPoints is not a function 当我从OnSourceChanged调用它时,出现以下错误: TypeError:this.constructPoints不是函数
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. 如您所见,我在最后一个代码段中注释了此代码,其中this.onDataSourceLoaded被调用。 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. 问题是您将函数传递给其他人,并且他们在未向您传递期望的this
参数的情况下调用了this
函数。 Try using an arrow function to capture this
尝试使用箭头功能捕获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. 在JavaScript中, this
是由调用方而不是函数的声明位置确定的。 See here and here for more 在这里和这里看到更多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.