我正在开发一个使用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);
}
问题是单击事件发生在文档对象中,而该上下文中不存在this.marker。
有什么方法可以处理我创建的SpeedMarker对象中的事件吗?
更改
google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow);
至
var self = this;
google.maps.event.addListener(this.marker, 'click', function () {
self.ShowInfoWindow();
});
或使用Function.bind
(警告:可能需要垫片):
google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow.bind(this));