[英]class property becomes undefined after adding an eventlistener inside the constructor
I am trying to create a class for drawing using typescript, but the property canvas
becomes undefined if I add an event listener inside the constructor.我正在尝试创建一个 class 用于使用 typescript 进行绘图,但是如果我在构造函数中添加事件侦听器,属性
canvas
将变为未定义。 here is my code:这是我的代码:
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);
}
}
here is the error:这是错误:
Canvas.js:7 Uncaught TypeError: Cannot read properties of undefined (reading 'getContext')
at HTMLCanvasElement.method1
You need to bind the callback.您需要绑定回调。 Either do:
要么做:
this.canvas.addEventListener("mousedown", this.method1.bind(this))
or或者
this.canvas.addEventListener("mousedown", () => this.method1())
In your inital code, you set the callback to a function pointer ( this.method1
), which will be executed with this
refering to its current value in the executing context.在您的初始代码中,您将回调设置为 function 指针 (
this.method1
), this
指针将通过引用其在执行上下文中的当前值来执行。 In a click handler, that should be the clicked element, so this
is not your object, but the HTML canvas element.在点击处理程序中,这应该是被点击的元素,所以
this
不是您的 object,而是 HTML canvas 元素。 And since the canvas has no property canvas
, you get the error.由于 canvas 没有属性
canvas
,您会收到错误消息。
By binding the function with bind()
, you get a new function, where this
refers to whatever you put into bind.通过将 function 与
bind()
,您将获得一个新的 function,其中this
指的是您放入绑定中的任何内容。
In an arrow function, this
always refers to what this
is where the arrow function is declared.在箭头 function 中,
this
始终指代箭头 function 声明this
位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.