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
});
ie without the this
in the function
parameters.
What is the correct way to access the itemCount
member variable?
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
}
});
The value of this
in the function is not the same as it is inside the class. You can either use fat arrow function or use bind(this)
to bind the function to the class.
this.itemPrices.forEach(function(prices){
if(prices.length != this.itemCount){
// handle error
}).bind(this);
You can make use of ES6's arrow functions to access this
. Anyways, do read this up to udnerstand to context of this
when it comes to JavaScript and using them within OOP in JS.
this.itemPrices.forEach((prices: number) => {
if (prices.length != this.itemCount){
// handle error
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.