JavaScript中的this与function中的this

 在写openlayers过程中遇到了Cannot read property 'hasFeatureAtPixel' of undefined.本以为是有相关包未导入,仔细检查后并没有缺什么,且通过打印发现map未定义.百思不得其解,后发现原来不是openlayers的问题,而是js的问题

在js中,函数中的this总指向调用它的对象.

js中,this指的是全局变量,假如全局变量没有此参数时相当于在此方法中重新定义,如果全局变量中有此参数那么this仍然绑定到外部函数的this变量上

方法调用时,函数绑定到了定义的对象属性上,其实相当于对象的一个方法,而this被绑定到该对象上.

详情可见

https://www.cnblogs.com/xzqbetter/p/7614618.html

以下为正确代码示例:

let that = this;
this.map.on('click', function(e) {
// console.log("hhhhhhhhhhhhhhh",this.map)
console.log(e.coordinate)
if (that.map.hasFeatureAtPixel(e.pixel)) {
var feature = that.map.getFeaturesAtPixel(e.pixel)
console.log('这里有信息')
}
})



原文地址:https://www.cnblogs.com/YST-study/p/14233934.html