我在这个问题上停了 4h,当 Google map 事件调用时,if
忽略了我的 bool。我需要给出参数不同的数据。也许世界上有人知道为什么?
console.log
同时点击后抛出:
true before click
stack.html:56[object HTMLDivElement]in listener
stack.html:62[object HTMLDivElement]bunga bunga
损坏的 boolean 值:
this.b = true;
...
console.log(this.b + " beafore click");
this.mapListener = google.maps.event.addListener(map, 'click', function(e) {
console.log(this.b + "in listener");
if (this.b==true) {
console.log(this.b + "true works");
tools[type](e.latLng, last_marker_origin);
this.b = false;
} else {
console.log(this.b + "bunga bunga");
//tools[type](e.latLng);
}
});
this
指的是我的对象中的“属性”,默认设置为 false,但当我更改选项时,它的标志为 true。
我先去 sleep 了。我早上会回复。
最佳答案
您的问题是,this
不再是对您的属性
的有效引用。处理特定问题的最简单方法是更改代码:
this.b = true;
var props = this;
console.log(this.b + " beafore click"); //Notice that "this" is still valid here
this.mapListener = google.maps.event.addListener(map, 'click', function(e) {
console.log(props.b + "in listener");
if (props.b == true) {
console.log(props.b + "true works");
tools[type](e.latLng, last_marker_origin);
props.b = false;
} else {
console.log(props.b + "bunga bunga");
//tools[type](e.latLng);
}
});
根本问题是,实际调用回调函数的代码位于完全不同的范围内,因此当该代码运行时,this
的含义发生了变化。设置引用并将其放入代码中将解决您的问题。
关于javascript - 如何在 Google map 监听器中使用 bool?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10324495/