引用在回调函数中更正此参考

时间:2016-06-03 11:54:29

标签: javascript google-maps typescript

我在Typescript中有一个类函数,它为Google地图添加了一个圆圈,并添加了一个事件监听器。在该侦听器中,我想引用this,将我添加侦听器的对象作为对象。 See this作为关于它如何在纯JS中工作的参考

不幸的是,Typescript阻止我引用正确的这个,我如何解决这个(问题,而不是这个)

public drawGeoFence(/* params removed */) : void {
    google.maps.event.addListener(circle, "mouseover", (event) => {
        this.showGeofenceInfoWindow(map, geofence, this); // <<- this!
    });
}

1 个答案:

答案 0 :(得分:2)

只需使用 function ,而不是箭头功能

public drawAThing(/* params removed */) : void {
    let self = this;
    //google.maps.event.addListener(circle, "mouseover", (event) => {
    google.maps.event.addListener(circle, "mouseover", function(event){
        self.showGeofenceInfoWindow(map, geofence, this); // <<- this!
    });
}

此外,要访问原始showGeofenceInfoWindow,我们需要更多编码...以将原始this保留在self变量中

相关问题