![](/img/trans.png)
[英]Angular 2 & Typescript: Cannot access class instance from event handler
[英]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.