Javascript TypeError:在成员数组上使用forEach时“这是未定义的”
我有一个类marketData: 但是,上面给出了一个错误类型ERROR:这是未定义的。我以这种方式检查itemPrices时遇到了完全相同的错误:Javascript TypeError:在成员数组上使用forEach时“这是未定义的”,javascript,angular,typescript,Javascript,Angular,Typescript,我有一个类marketData: 但是,上面给出了一个错误类型ERROR:这是未定义的。我以这种方式检查itemPrices时遇到了完全相同的错误: this.itemPrices.forEach(function(prices){ if(prices.length != this.itemCount){ // handle error }); i、 e.在功能参数中没有此选项 访问itemCount成员变量的正确方法是什么?
this.itemPrices.forEach(function(prices){
if(prices.length != this.itemCount){
// handle error
});
i、 e.在功能参数中没有此选项
访问itemCount成员变量的正确方法是什么?函数中的值与类中的值不同。可以使用fat arrow函数或bindthis将函数绑定到类
this.itemPrices.forEach(function(prices){
if(prices.length != this.itemCount){
// handle error
}).bind(this);
这是因为你们使用forEach的方式。用下面的方法代替。建议在使用typescript类时始终使用箭头函数,否则您将继续遇到此问题
this.itemPrices.forEach((prices) =>{
if(prices.length != this.itemCount){
// handle error
}
});
您可以使用ES6访问此文件。无论如何,当涉及到JavaScript并在JS中的OOP中使用它们时,一定要读到udnerstand的上下文
this.itemPrices.forEach((prices: number) => {
if (prices.length != this.itemCount){
// handle error
});
});
this.itemPrices.forEach((prices) =>{
if(prices.length != this.itemCount){
// handle error
}
});
this.itemPrices.forEach((prices: number) => {
if (prices.length != this.itemCount){
// handle error
});
});