簡體   English   中英

TypeScript - 如何從事件處理程序方法訪問類實例

[英]TypeScript - How to access the class instance from event handler method

在下面的代碼片段,我有一個打字稿類和實例方法buz是畫布監聽click事件。

buz方法中的this關鍵字是指事件的目標對象(canvas)。

如何從buz方法訪問foo實例?

    class Foo {
        constructor(private _canvas: HTMLCanvasElement, private _message: string) {

        }

        public bar(): void {
            this._canvas.addEventListener(`click`, this.buz);
        }

        private buz(e: MouseEvent): void {
            console.info(`After click event, 'this' refers to canvas and not to the instance of Foo:`);
            console.info(this);
            console.warn(`Message is: "${this._message}"`); // error
        }
    }

    window.addEventListener('load', () => {
        let canvas = <HTMLCanvasElement> document.getElementById('canvas');
        let foo = new Foo(canvas, "Hello World");
        foo.bar();
    });

我的tsconfig.json有以下設置:

"compilerOptions": {
  "module": "commonjs",
  "target": "es5",
  "sourceMap": true
},

當您將其作為參數傳遞時,您的上下文在buz方法中丟失。 您可以使用箭頭功能來實現這一目標。 箭頭功能將保存上下文。

public bar(): void {
    this._canvas.addEventListener(`click`, (evt) => this.buz(evt));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM