我正在开发使用Google Maps API的应用程序。我以前没有使用javascript的经验。我要做的是以下内容:
function SpeedMarker(position) {
this.speed = 50;
this.marker = new google.maps.Marker({
position: position,
map: map,
icon: 'http://maps.google.com/mapfiles/markerA.png',
zIndex: Math.round(position.lat() * -100000) << 5
});
google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow)
}
SpeedMarker.prototype.ShowInfoWindow = function () {
var contentString = 'stuff';
infowindow = new google.maps.InfoWindow({
content: contentString
});
infowindow.open(map, this.marker);
}
问题是click事件发生在文档对象中,而this.marker在该上下文中不存在。
有没有办法在我创建的SpeedMarker对象中处理事件?
答案 0 :(得分:5)
更改
google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow);
到
var self = this;
google.maps.event.addListener(this.marker, 'click', function () {
self.ShowInfoWindow();
});
或使用Function.bind
(警告:may require shim):
google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow.bind(this));