【发布时间】: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
},
【问题讨论】:
-
this.buz.bind(this)或() => this.buz() -
@AndrewLi 非常相似,但是这个使用的是 TS 和它的箭头函数。不需要
bind
标签: javascript typescript