Mastro Mastro - 3 months ago 8
TypeScript Question

How do I reference this parent method in my TypeScript class from an array's ForEach loop?

So I'm trying to call a method in a TypeScript class from within an array's ForEach loop. However, it seems that I can't figure out how to scope in the right 'this' for the parent class.

What I want to do is call the getFeatureAmount method from the survey.answerKey.q2SelectedValues.forEach(function(value)){ ... });
like this:

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


But I get that 'this' is undefined and can't find the getFeatureAmount. As a temporary workaround, I have to call getFeatureAmount as a callback function.

private getFeatureAmount = (value: string): number => {
return this._subtotalPlatform += parseInt(value) * this._baseRate.local;
}

survey.answerKey.q2SelectedValues.forEach(this.getFeatureAmount);


It's just not what i really wanted to do. So I'm wondering is there any way to do this with a lambda ()=>{}?

Answer

Try changing

survey.answerKey.q2SelectedValues.forEach(function(value){
   subtotal_ui = this.getFeatureAmount(value, subtotal_ui); //ERROR HERE. 'this' is undefined
})

to

survey.answerKey.q2SelectedValues.forEach((value) => {
   // now this will be refer to the instance of your CalculationService class
   subtotal_ui = this.getFeatureAmount(value, subtotal_ui);
});