在事件函数中引用“ this”,同时仍然可以删除事件TypeScript

时间:2019-02-18 19:00:13

标签: javascript typescript keyboard-events

我正在用TypeScript制作此游戏,并尝试添加和删除“ keydown”事件。事件函数引用“ this”,女巫是文档,但是我试图引用对象实例。

如何实现?

class Player {
    board: Board = new Board();
    pice: Pice = new Pice();

    constructor() {
        this.addKeyEvents();
    }

    addKeyEvents(): void {
        document.addEventListener("keydown", this.keyClick);
    }

    removeKeyEvents(): void {
        document.removeEventListener("keydown", this.keyClick);
    }

    keyClick(event: KeyboardEvent): void {
        console.log(this); // #document

        switch (event.keyCode) {

            // Left
            case 37:
                this.pice.move(-1, 0, this.board);
                break;
        }

    }

}

1 个答案:

答案 0 :(得分:0)

您必须将函数绑定到实例或使用箭头函数提供适当的上下文。

// Binding way.
class Player {
    constructor() {
        this.addKeyEvents();
        // Bind the function to `this` context.
        this.keyClick = this.keyClick.bind(this)
    }

    addKeyEvents(): void {
        document.addEventListener("keydown", this.keyClick);
    }

    keyClick(event: KeyboardEvent): void { /* ... */ }
}

// Arrow function way.
class Player {
    constructor() {
        this.addKeyEvents();
    }

    addKeyEvents(): void {
        // Create an intermediary arrow function that will keep the context.
        document.addEventListener("keydown", event => this.keyClick(event));
    }

    keyClick(event: KeyboardEvent): void { /* ... */ }
}