0

我停在这个问题4h,if忽略了我的BOOL当谷歌地图事件调用。我需要给参数不同的数据。也许在这个世界上有人知道为什么?如何在谷歌地图监听器中使用bool?

点击在同一时间后

的console.log投:

true beafore click 
stack.html:56[object HTMLDivElement]in listener 
stack.html:62[object HTMLDivElement]bunga bunga 

破布尔:

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,但是当我改变它的选项标志为真。

我现在睡觉了。我会在早上回答。

回答

1

您的问题是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意义代码运行时已更改。设置参考并将其放入代码将解决您的问题。

+0

我不得不今天检查,它的工作原理。谢谢回复。你是第一个:) – roza 2012-04-25 22:41:19

+0

令人惊讶的是,有多少JavaScript问题归结为范围问题。很难进入你的脑海,它应该成为一个问题,但是一旦你意识到它,你将会更容易编写JavaScript。好的答案:) – 2012-04-26 06:45:09

1

这里的问题是this的范围。当您处于单击事件处理函数this中时,不再引用您的属性对象,而是引用该事件处理函数。事件处理程序是所谓的closure

您的问题有两种可能的解决方案。

  1. 使用局部变量(var b而不是this.b)为你的价值,局部变量被复制在一个封闭的,所以值可以内部和封闭的外使用:

    var b = true; 
    console.log(b + " beafore click"); 
    this.mapListener = google.maps.event.addListener(map, 'click', function(e) { 
        console.log(b + "in listener"); 
        if (b==true) { 
         console.log(b + "true works"); 
         tools[type](e.latLng, last_marker_origin); 
         b = false; 
        } else { 
         console.log(b + "bunga bunga"); 
         //tools[type](e.latLng); 
        } 
    }); 
    
  2. 在一个局部变量保存this,这是一个很常见的技术,以避免划定范围的问题:

    //save this in a locale variable, now 'me' provides access to this scope 
    var me = this; 
    me.b = true; 
    console.log(me.b + " beafore click"); 
    this.mapListener = google.maps.event.addListener(map, 'click', function(e) { 
        console.log(me.b + "in listener"); 
        if (me.b==true) { 
         console.log(me.b + "true works"); 
         tools[type](e.latLng, last_marker_origin); 
         me.b = false; 
        } else { 
         console.log(me.b + "bunga bunga"); 
         //tools[type](e.latLng); 
        } 
    }); 
    
+0

第一个选项不起作用,因为它不会将properties.b成员的值设置为false。 – 2012-04-25 22:33:58

+0

确实如此,但并非绝对必需。您可能想要使用第二个选项,但如果您只有一个值,那么第一个选项就可以。 – Odi 2012-04-25 22:40:12