我在typescript中全局定义了一个变量,在一个函数中,我无法使用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;
我该如何解决这个问题?
在下面的评论框中,我发现了很多我不想要的理论。我正在寻找解决方案。
通过用箭头函数定义=>
替换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;
})