Mas*_*tro 1 javascript foreach this typescript
因此,我试图从数组的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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是我知道'this'是未定义的,找不到getFeatureAmount。作为临时的解决方法,我必须将getFeatureAmount用作回调函数。
private getFeatureAmount = (value: string): number => {
return this._subtotalPlatform += parseInt(value) * this._baseRate.local;
}
survey.answerKey.q2SelectedValues.forEach(this.getFeatureAmount);
Run Code Online (Sandbox Code Playgroud)
这不是我真正想做的。所以我想知道有什么方法可以使用lambda()=> {}吗?
尝试改变
survey.answerKey.q2SelectedValues.forEach(function(value){
subtotal_ui = this.getFeatureAmount(value, subtotal_ui); //ERROR HERE. 'this' is undefined
})
Run Code Online (Sandbox Code Playgroud)
至
survey.answerKey.q2SelectedValues.forEach((value) => {
// now this will be refer to the instance of your CalculationService class
subtotal_ui = this.getFeatureAmount(value, subtotal_ui);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1737 次 |
| 最近记录: |