我在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的含义在该代码运行时已更改。设置引用并将其放在代码中将解决您的问题。

09-30 13:28
查看更多