【问题标题】:TypeScript - How to access the class instance from event handler methodTypeScript - 如何从事件处理程序方法访问类实例
【发布时间】:2017-06-18 02:31:24
【问题描述】:

在下面的代码 sn-p 中,我有一个 TypeScript 类,实例方法 buz 是 canvas 的 click 事件的侦听器。

buz 方法中的this 关键字指的是事件的目标对象(画布)。

如何通过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
},

【问题讨论】:

标签: javascript typescript


【解决方案1】:

当您将 buz 方法作为参数传递时,您的上下文会丢失。您可以使用箭头函数来实现这一点。箭头函数将保存上下文。

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

【讨论】:

  • 谢谢。我将方法调用更改为:this._canvas.addEventListener('click', evt =&gt; this.buz(evt));
  • 你拯救了我的一天
猜你喜欢
  • 2016-09-17
  • 2023-03-07
  • 1970-01-01
  • 2010-09-13
  • 2015-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多