我在4h停了下来,当调用Google maps事件时if
忽略了我的bool。我需要输入不同的数据。也许世界上有人知道为什么?
单击后同时抛出console.log
:
true before click
stack.html:56[object HTMLDivElement]in listener
stack.html:62[object HTMLDivElement]bunga bunga
碎 bool(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。我现在去睡觉。我会在早上回答。
最佳答案
您的问题是this
不再是对properties
的有效引用。解决特定问题的最简单方法是更改代码:
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
的含义在该代码运行时已更改。设置引用并将其放在代码中将解决您的问题。