代码之家  ›  专栏  ›  技术社区  ›  Teight

我的JavaScript代码在尝试使用keydown事件处理程序更改类中的变量时遇到问题

  •  0
  • Teight  · 技术社区  · 8 年前

    在我的更新中,posX应该在 W 键被按下,但什么也没发生。如果我去掉If语句,只要在调用update函数时对其进行更改,它就会工作。

    class FPlayer {
    
        constructor(windowWidth, windowHeight, width, height, posX, posY) {
    
            this.width = width;
            this.height = height;
            this.posX = posX;
            this.posY = posY;
            this.windowWidth = windowWidth;
            this.windowHeight = windowHeight;
            this.x = 0;
    
            addEventListener("keydown", this.handler);
        }
    
        update() {
    
            if(this.x == 87) {
    
                this.posX += 2;
            }
        }
        draw() {
    
            c.beginPath();
            c.fillStyle = "blue";
            c.fillRect(this.posX, this.posY, this.width, this.height);
            c.closePath();
        }
    
        handler(event) {
    
            this.x = event.keyCode;
        }
    }
    
    1 回复  |  直到 5 年前
        1
  •  0
  •   Barmar    8 年前

    这行不通:

    addEventListener("keydown", this.handler);
    

    这只是将函数添加为处理程序,而不是将其绑定到正确的对象。使用:

    addEventListener("keydown", this.handler.bind(this));