javascript - 如何从数组的 ForEach 循环中引用我的 TypeScript 类中的这个父方法?

标签 javascript typescript foreach this

所以我试图从数组的 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/

相关文章:

javascript - 仅在需要时加载 javascript 函数

javascript - 打印收据样式

c# - 改进编码周期

javascript - 如何自引用 NodeJS 模块?

javascript - 我应该为不同的设备单独制作 "responding script"吗?

用于淡入淡出 View 的 Angular 4 动画

typescript - 是否有 OpenAPI 3 的官方 Typescript 类型定义?

typescript - Firestore delete a field in an object is a field of another object inside an array

php - 语法错误,意外 'endforeach' (T_ENDFOREACH),期望文件结尾(在我的 slider View 中 - 轮播)

c# - 返回枚举名称基值