【问题标题】:Reference correct this within callback function在回调函数中引用更正此
【发布时间】:2016-10-03 11:34:52
【问题描述】:

我在 Typescript 中有一个类函数,它向谷歌地图添加一个圆圈并添加一个事件侦听器。在该侦听器中,我想引用this,分配我要添加侦听器的对象。 See this 作为在纯 JS 中如何工作的参考

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

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

【问题讨论】:

标签: javascript google-maps typescript


【解决方案1】:

只使用 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 变量中

【讨论】:

  • 你为什么不能用这个showGeofenceInfoWindow
  • 因为this 现在引用本地函数范围而不是类
  • @Blubberguy22 这将来自不同的上下文。 Typescript 对箭头函数所做的 magic 将不会被应用...查看此以了解详细信息如何basarat.gitbooks.io/typescript/content/docs/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 2017-10-29
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多