【发布时间】:2021-05-17 16:47:11
【问题描述】:
我有一个由 chartJs 提供支持的画布来显示图表。我定义了一个 onmousemove 函数,如下所示 操纵变量
myVariable = false;
ctx: any;
@ViewChild("mychart") mychart;
ngAfterViewInit()
{
this.canvas.onmousemove = function(e) {
this.myVariable = true;
};
}
不幸的是,它显示 myVairable 未定义。我如何在 onmousemove 触发时访问此变量?我还尝试了如下所示的 bind(this),但没有成功。
this.canvas.onmousemove = (function(e) {
console.log(this.myVariable);
}).bind(this)
Stackblitz 示例https://stackblitz.com/edit/angular-chart-js-zzqumr
【问题讨论】:
-
如果你使用箭头函数而不是 function(e) 我相信会解决它。函数有自己的 this 上下文,但箭头函数会自动绑定并且没有自己的 this。
标签: javascript angular typescript html5-canvas chart.js