所以我试图从数组的 ForEach 循环中调用 TypeScript 类中的方法。但是,我似乎无法弄清楚如何为父类确定正确的“this”范围。
我想做的是从 survey.answerKey.q2SelectedValues.forEach(function(value)){ ... }); 调用 getFeatureAmount 方法 像这样:
export class CalculationService {
private _baseRate: BaseRate;
private _subtotalPlatform: number = 0;
constructor(){
this._baseRate = new BaseRate(125, 60);
};
//This is the method I'm trying to call
private getFeatureAmount = (value: string, sub: number): number => {
return sub += parseInt(value) * this._baseRate.local;
}
public calculate(survey: Survey){
let subtotal_ui: number = 0;
subtotal_ui = (parseInt(survey.answerKey.q1SelectedValues[0]) * 5);
survey.answerKey.q2SelectedValues.forEach(function(value){
subtotal_ui = this.getFeatureAmount(value, subtotal_ui); //ERROR HERE. 'this' is undefined
});
return subtotal_ui + this._subtotalPlatform;
}
}
但我知道“this”未定义,无法找到 getFeatureAmount。作为临时解决方法,我必须调用 getFeatureAmount 作为回调函数。
private getFeatureAmount = (value: string): number => {
return this._subtotalPlatform += parseInt(value) * this._baseRate.local;
}
survey.answerKey.q2SelectedValues.forEach(this.getFeatureAmount);
这不是我真正想做的。所以我想知道有没有办法用 lambda ()=>{} 来做到这一点?
最佳答案
尝试改变
survey.answerKey.q2SelectedValues.forEach(function(value){
subtotal_ui = this.getFeatureAmount(value, subtotal_ui); //ERROR HERE. 'this' is undefined
})
到
survey.answerKey.q2SelectedValues.forEach((value) => {
// now this will be refer to the instance of your CalculationService class
subtotal_ui = this.getFeatureAmount(value, subtotal_ui);
});
关于javascript - 如何从数组的 ForEach 循环中引用我的 TypeScript 类中的这个父方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39413781/