简体   繁体   中英

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. 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. In a click handler, that should be the clicked element, so this is not your object, but the HTML canvas element. And since the canvas has no property canvas , you get the error.

By binding the function with bind() , you get a new function, where this refers to whatever you put into bind.

In an arrow function, this always refers to what this is where the arrow function is declared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM