我在TypeScript中有一个简单的if-else代码。但在某些代码中无法访问它。它显示了以下错误,
"无法读取未定义的属性(正在读取"setNewsProvider"(">
代码
if (this.newsShow != null) {
if (this.glbNews.nIds == null) {
this.setNewsProvider(); //Accessible Here
}
else {
if (this.newsShow.EmpLst == null) {
this.setNewsProvider(); // Accessible Here
}
else {
if (this.newsShow.LCL == "X300") {
if (this.newsShow.MXD == "N300") {
var prd1 = this.newsShow.ProducerChk;
this.glbNews.PrdNcc.forEach(function (value) {
if (value == prd1) {
this.setNewsProvider(); //Un accessible here.. "Cannot read properties of undefined (reading 'setNewsProvider')"
}
})
}
else {
//Some code here
})
}
}
}
}
}
在forEach
循环中,您输入一个函数,该函数有自己的值。为了避免这个问题,JS程序员过去经常编写
const that = this;
在入口点,然后使用that.setNewsProvider()
,这样更具本地作用域的this就不会覆盖它。如果使用箭头函数,问题将被避免,因为这些函数没有自己的本地this值。
this.glbNews.PrdNcc.forEach((value) => {
if (value == prd1) {
this.setNewsProvider();
}
})
您使用了一个正则函数function() {}
,而不是箭头函数() => {}
。常规函数不能捕获this
关键字,但箭头函数可以捕获
因为this
没有被捕获,所以您会得到Cannot read properties of undefined
错误,因为function(value)
内部的this
与外部的this
不同。CCD_ 11的任何性质和函数都不会被引入到正则函数中。
修复方法是使用箭头功能,即
...
this.glbNews.PrdNcc.forEach((value) => {
...
});
...
这里有一篇文章更彻底地解释了这两种功能类型之间的区别:
"箭头函数"one_answers"函数"等效/可互换吗?