![](/img/trans.png)
[英]javascript constructor property becomes undefined after event is called
[英]class property becomes undefined after adding an eventlistener inside the constructor
我正在尝试创建一个 class 用于使用 typescript 进行绘图,但是如果我在构造函数中添加事件侦听器,属性canvas
将变为未定义。 这是我的代码:
export class Canvas {
private canvas: HTMLCanvasElement;
constructor() {
this.canvas = document.getElementById("main_canvas") as HTMLCanvasElement;
this.canvas.addEventListener("mousedown", this.method1)
}
method1() {
let context = this.canvas.getContext("2d") as CanvasRenderingContext2D;
context.moveTo(0, 0);
}
}
这是错误:
Canvas.js:7 Uncaught TypeError: Cannot read properties of undefined (reading 'getContext')
at HTMLCanvasElement.method1
您需要绑定回调。 要么做:
this.canvas.addEventListener("mousedown", this.method1.bind(this))
或者
this.canvas.addEventListener("mousedown", () => this.method1())
在您的初始代码中,您将回调设置为 function 指针 ( this.method1
), this
指针将通过引用其在执行上下文中的当前值来执行。 在点击处理程序中,这应该是被点击的元素,所以this
不是您的 object,而是 HTML canvas 元素。 由于 canvas 没有属性canvas
,您会收到错误消息。
通过将 function 与bind()
,您将获得一个新的 function,其中this
指的是您放入绑定中的任何内容。
在箭头 function 中, this
始终指代箭头 function 声明this
位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.