簡體   English   中英

如何從數組的ForEach循環中的TypeScript類中引用此父方法?

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

因此,我試圖從數組的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);
});
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將不是對象/類。 返回或使用lambda函數作為參數,如果你想this是含類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM