2015-05-07 79 views
0

我正在使用google-maps javascript v.3 API。我只是在这里展示了一个聪明的代码,我认为这是唯一与我的问题相关的部分。如何通过google.maps.event.addDomListener调用对象方法时访问对象成员变量

我不明白为什么对象GMaps的成员变量似乎调用gmaps.initMap时,按如下google.maps.event.addDomListener(window, 'load', gmaps.initMap);

我已经实现的功能GMaps.test,看看成员变量GMaps.LATIDX正确地提醒dissapear,这确实按预期工作。但是,当我尝试通过google.maps.event.addDomListener(window, 'load', gmaps.initMap);呼叫功能GMaps.initMap中的相同成员变量时,会提醒“未定义”,我不明白为什么。

<!DOCTYPE html> 
<html> 
<head> 

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script> 

var GMaps = function() { 
    this.map = null; 
    // constants 
    this.LATIDX = 0; // 2d array index constant (latitude index) 
    this.LNGIDX = 1; // 2d array index constant (longtitude index) 

    this.test = function() { 
     alert(this.LATIDX); // THIS ALERTS 0 AS EXPECTED 
    } 

    this.initMap = function(aActor, aLatLngCoord, aLatLngCenter) { 
     alert(this.LATIDX); // THIS ALERTS "undefined", I DON'T UNDERSTAND WHY. 
    } 
} 
</script> 

gmaps = new GMaps(); 
gmaps.test(); 
google.maps.event.addDomListener(window, 'load', gmaps.initMap); 

</head> 
</html> 

回答

1

当您使用addDomListener/addListener的API将在听者已经被应用到该对象的上下文中执行回调(在你的代码是window),this将指向这个对象。

要改变上下文使用绑定(或应用),并使用所需的对象(gmaps)作为第一个参数:

google.maps.event.addDomListener(window, 
           'load', 
           function(){ 
            gmaps.initMap.call(gmaps); 
           }); 

当该功能是一个特定对象的方法,如在您的代码,它的足以使用执行所需功能(对象方法)的回调,那么您不需要更改上下文:

google.maps.event.addDomListener(window, 
           'load', 
           function(){//context is window 
            gmaps.initMap();//context is gmaps 
           });