在以下代码片段中,我有一个TypeScript类,实例方法buz是canvas的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
},
this.buz.bind(this)
or() => this.buz()
- Andrew Libind
。 - Poulad