JavaScript事件处理程序范围

use*_*875 2 javascript

我正在开发一个使用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);
}
Run Code Online (Sandbox Code Playgroud)

问题是click事件发生在文档对象中,而this.marker在该上下文中不存在.

有没有办法在我创建的SpeedMarker对象中处理事件?

Mat*_*all 5

更改

google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow);
Run Code Online (Sandbox Code Playgroud)

var self = this;
google.maps.event.addListener(this.marker, 'click', function () {
    self.ShowInfoWindow();
});
Run Code Online (Sandbox Code Playgroud)

或使用Function.bind(警告:可能需要垫片):

google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow.bind(this));
Run Code Online (Sandbox Code Playgroud)