如何从数组的ForEach循环中引用我的TypeScript类中的此父方法?

时间:2016-09-09 14:21:05

标签: 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()=> {}?

2 个答案:

答案 0 :(得分:4)

尝试更改

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

答案 1 :(得分:2)

var o = {
    one: function() { return this; },
    two: () => { return this; },
    three() { return this; },
    four() { return function () { return this; }; },
    five() { return () => { return this; }; }
}

o.one() === o
o.two() === window
o.three() === o
o.four()() === window
o.five()() === o

不要使用lambda语法声明方法,因为this不是对象/类。如果希望this成为包含类,则返回或使用lambda函数作为参数。