在 Typescript 原始函数中访问 'this'

Accessing 'this' inside Typescript raw function

我有一个 Angular 6 应用程序,它使用出色的 ngx-charts 框架来显示图表。这个图表组件让我可以像这样指定工具提示格式功能:

<ngx-charts-bar-vertical [xAxisTickFormatting]="dateTickFormatting" >
</ngx-charts-bar-vertical>

然后在父组件中定义格式化函数class:

  dateTickFormatting(val: string): string {
    return val.toUpperCase();
  }

当我尝试从此格式化程序函数访问父组件 class 中的值时出现问题:

  public testVar: string = 'This is a test variable';

  dateTickFormatting(val: string): string {
    console.log(this.testVar);
    return val.toUpperCase();
  }

在这种情况下,testVar 将是未定义的。

我知道 'this' 引用丢失了,因为 ngx-chartsdateTickFormatting 作为 'raw' 函数引用。有没有办法保留对父 classes' this 的引用,禁止修改图表框架?

你应该使用箭头函数

如果你这样做

  public testVar: string = 'This is a test variable';

  dateTickFormatting = (val: string): string => {
    console.log(this.testVar);
    return val.toUpperCase();
  }

它将使用正确的 this 并工作。

我建议阅读一些关于箭头函数的内容https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions