-2

I have defined a variable globally in typescript, within one function I am not able to get that variable using this keyword

This is my code

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;
})

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

This is how I have declared polygonSeries variable

public polygonSeries:any;

How can I solve this issue?

In the below answer in comment box, I came across lots of theory which I don't want. I am looking for solution.

R15
  • 13,982
  • 14
  • 97
  • 173
  • 2
    The solution is to use arrow function `(latitude, target) => { ... }` instead of normal `function` declaration. But you should try to understand the theory, to see _why_ this is a solution. – CRice Jul 17 '20 at 16:43
  • Thank you. Now I am able to access. You can write your comment as answer. – R15 Jul 17 '20 at 17:03

1 Answers1

1

Fixed by replacing function definition with arrow function definition => as below

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;
})
user120242
  • 14,918
  • 3
  • 38
  • 52
R15
  • 13,982
  • 14
  • 97
  • 173