如何修复班级中未定义的错误?

时间:2019-01-14 20:25:08

标签: javascript html

我想为键盘输入创建一个Javascript类。我正在尝试测试我的课程,但出现了未定义的错误。

index.html的内容

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test Keyboard</title>
    <style type="text/css" media="screen">
      canvas { border: 1px solid; }
    </style>
  </head>
  <body>
    <h1 id ="title">Test Keyboard</h1>
    <script src="src/input.js"></script>
  </body>
</html>

input.js的内容

'use strict';

class Keyboard {

    constructor() {
        this.keysPressed = {}
        this.translateKeyCode = {
            49: 0x1,  // 1
            50: 0x2,  // 2
            51: 0x3,  // 3
            52: 0x4,  // 4
            81: 0x5,  // Q
            87: 0x6,  // W
            69: 0x7,  // E
            82: 0x8,  // R
            65: 0x9,  // A
            83: 0xA,  // S
            68: 0xB,  // D
            70: 0xC,  // F
            90: 0xD,  // Z
            88: 0xE,  // X
            67: 0xF,  // C
            86: 0x10  // V
        }

    }

    onNextKeyPressed(code) {
        //Override this in Fx0A - LD Vx, K
    }

    isPressed(event) {
        return this.keysPressed[this.translateKeyCode[event.keyCode]];

    }

    isDown(event) {
        console.log(`Pressed ${event.keyCode}`)
        this.keysPressed[this.translateKeyCode[event.keyCode]] = 1;
        this.onNextKeyPressed(event.keyCode);
        // We only want onNextKeyPressed to run once
        // After a Fx0A opcode
        this.onNextKeyPressed = function() {};
    }

    isUp(event) {
        console.log(`Released ${event.keyCode}`)
        delete this.keysPressed[this.translateKeyCode[event.keyCode]];
    }

}

let keyboard = new Keyboard();

window.addEventListener("keydown", keyboard.isDown);
window.addEventListener("keyup", keyboard.isUp);

预期结果是代码可以正确运行。

实际结果是在按键时这些行出现Javascript未定义错误。

this.keysPressed[this.translateKeyCode[event.keyCode]] = 1;
this.onNextKeyPressed(event.keyCode);
delete this.keysPressed[this.translateKeyCode[event.keyCode]];

1 个答案:

答案 0 :(得分:1)

尝试保留绑定,这对于ES6来说相当简单:

window.addEventListener("keydown", (ev) => keyboard.isDown(ev));
window.addEventListener("keyup", (ev) => keyboard.isUp(ev));

老式的对比方式:

window.addEventListener("keydown", function(ev) { keyboard.isDown(ev) });
window.addEventListener("keyup", function(ev) { keyboard.isUp(ev) });