情况
公司加班撸前端代码,发现有一个js内调取自身方法报错
this.XX is not defined
__draw: function(redraw,mapMarkersArray){
let that = this;
mapMarkersArray.forEach(function(val,index,arr) {
if(val.type == 1)
{
if(redraw)
{
that.removeCircles()
}
}
})
}
原因
直接导致的原因是“forEach”方法,forEach方法第二个参数为指定对象,如果没有填写则默认指向window
解决
__draw: function(redraw,mapMarkersArray){
let that = this;
mapMarkersArray.forEach(function(val,index,arr) {
if(val.type == 1)
{
if(redraw)
{
that.removeCircles()
}
}
},this)
}
本文探讨了在JavaScript中使用forEach方法时遇到的this指向问题,详细解释了问题产生的原因及解决方案,即通过显式地将this绑定到回调函数的上下文来避免默认指向window的问题。
491

被折叠的 条评论
为什么被折叠?



