【问题标题】:access 'this' inside d3 call back with angular 7使用角度 7 访问 d3 回调中的“this”
【发布时间】:2019-11-21 02:03:26
【问题描述】:

我在 angular 指令中有以下代码,我想访问回调函数中的类级别变量,所以我使用了箭头函数,但“this”仍然没有指向指令。

this.itemRects.selectAll('rect')
            .data(this.visItems, (d) => {
                return d.id + this.x;
            })

我在调试器的返回语句 处添加了调试器,它显示此指向数据数组。

如何在回调函数中访问指令级别“this”?

【问题讨论】:

  • 这个代码是在另一个箭头函数里面吗?你可以尝试做 let self = this;然后用 self 代替 this。
  • 代码在类级函数内

标签: javascript angular typescript


【解决方案1】:

在回调函数中,this指的是回调函数对象。你可以像这样在回调函数之外声明一个变量:

var self = this;

并在回调函数中使用 self 而不是 this 来访问类变量。

请查看以下链接以使用箭头符号在回调函数中绑定类变量:How to use arrow functions (public class fields) as class methods?

试试:

this.itemRects.selectAll('rect')
            .data(this.visItems, (d,x) => {
                return d.id + x;
            })

【讨论】:

  • 我正在使用箭头函数,我不应该能够在不使用变量的情况下访问“this”吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-14
  • 2016-07-20
  • 2012-01-02
  • 2019-05-19
  • 2021-12-30
相关资源
最近更新 更多