首页 > 解决方案 > 在打字稿的特定代码片段中使用此关键字无法访问全局变量

问题描述

我在打字稿中全局定义了一个变量,在一个函数中我无法使用this关键字获取该变量

这是我的代码

imageTemplate.adapter.add("latitude", function(latitude, target) {
  const ctx = target.dataItem.dataContext as any;
  let polygon = this.polygonSeries.getPolygonById(ctx.id);
  if(polygon){
    return polygon.visualLatitude;
   }
   return latitude;
})

this.polygonSeries.getPolygonById(ctx.id);. Property polygonSeries does not exist.

这就是我声明polygonSeries变量的方式

public polygonSeries:any;

我该如何解决这个问题?

在评论框中的以下答案中,我遇到了很多我不想要的理论。我正在寻找解决方案。

标签: typescriptvariables

解决方案


通过用箭头函数定义替换function定义来修复,=>如下所示

imageTemplate.adapter.add("latitude", (latitude, target) => {
  const ctx = target.dataItem.dataContext as any;
  let polygon = this.polygonSeries.getPolygonById(ctx.id);
  if(polygon){
    return polygon.visualLatitude;
  }
  return latitude;
})

推荐阅读