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;
})
推荐阅读
- postgresql - Postgres:如何在不影响引用它的其他 MV 的情况下更改 MV 的名称?
- node.js - 尝试在 Angular UI 中显示时,获取的已排序 API 数据(NodeJs &Mongoose)未按排序顺序显示
- javascript - 显示更新的表格而不刷新或重新加载页面
- javascript - 如何将日期值转换为天数
- csv - 使用 Simple Data Writer 将响应数据与其他标签一起保存
- javascript - 使用按钮将每个 td 单元格文本复制到剪贴板
- php - 你如何在 PHP 中发布 JSON 数据?(将原始 cURL 代码转换为 PHP)
- aws-api-gateway - 未从 API Gateway URL 获取标头
- scala - 在 RoundRobinPool 中获取所选演员?
- c# - 在 .NET 5.0 上向 Windows 窗体添加配置