Skip to content
Advertisement

TypeError: “this is undefined” When using forEach on member array

I have a class marketData:

export class marketData {
    id: number;
    denomCount: number;
    itemCount: number;
    conversionRates: Array<number> = [];
    conversionRateToLowest: Array<number> = [];
    itemPrices: Array<Array<number>> = [];
}

I would like to define a member function for it, validate(), that checks that the values of the class are set properly. I wrote part of this method to check itemPrices:

this.itemPrices.forEach(function(this, prices){
          if(prices.length != this.itemCount){
              // handle error 
          });

However, the above gives me a ERROR TypeError: "this is undefined". I got the exact same error trying to check itemPrices in this manner:

this.itemPrices.forEach(function(prices){
          if(prices.length != this.itemCount){
              // handle error
          });

i.e. without the this in the function parameters.

What is the correct way to access the itemCount member variable?

Advertisement

Answer

Its because of the the way you are using forEach. Use Arrow Functions instead like below. And its recommended that when using typescript classes always use arrow functions else you will keep running into this problem.

this.itemPrices.forEach((prices) =>{
          if(prices.length != this.itemCount){
              // handle error
            }
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement