在下面的代码片段中,我有一个TypeScript 类和实例方法buz
是画布的监听器'click
event.
this
关键字在buz
方法指的是事件的目标对象(画布)。
如何访问foo
实例来自buz
method?
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();
});
My tsconfig.json
有这些设置:
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"sourceMap": true
},
你的上下文丢失了buz
方法,当您将其作为参数传递时。您可以使用箭头函数来实现这一点。箭头函数将保存上下文。
public bar(): void {
this._canvas.addEventListener(`click`, (evt) => this.buz(evt));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)