Uncaught TypeError не является методом класса функции

Я новичок в JavaScript и получаю такую ​​ошибку:

Uncaught TypeError: this.move is not a function

ТАК не позволит мне публиковать, если мой вопрос в основном код, поэтому вот ссылка на файл в github:https://github.com/pianocomposer321/Dodger.js/blob/master/player.js

Ошибка возникает в первом операторе case в onKeyPressed функция, когда он пытается вызвать this.move().

class Player {
    constructor(width, height, cvs) {
        this.width = width;
        this.height = height;
        this.cvs = cvs;
        this.ctx = this.cvs.getContext("2d");
        this.x = this.cvs.width / 2;
        this.y = this.cvs.height - this.height;

        document.addEventListener("keydown", this.onKeyPressed);
    }

    draw() {
        this.ctx.fillRect(this.x, this.y, this.width, this.height);
    }

    move(x, y) {
        this.x += x;
        this.y += y;
    }

    onKeyPressed() {
        switch (window.event.keyCode) {
            case 37:
                this.move(-5, 0);
                break;
            case 38:
                this.move(0, 5);
                break;
            case 39:
                this.move(5, 0);
                break;
            case 40:
                this.move(0, -5);
                break;
        }
    }
}

export { Player };

Заранее спасибо!

1 ответ

Решение

Слушатель Addevent меняет это. Вам нужно использовать привязку.

         class Player {
    constructor(width, height, cvs) {
        this.x = 0;
        this.y = 0;

        document.addEventListener("keydown", this.onKeyPressed.bind(this));
    }

    move(x, y) {
        this.x += x;
        this.y += y;
        console.log(this.x, this.y);
    }

    onKeyPressed() {
        switch (window.event.keyCode) {
            case 37:
                this.move(-5, 0);
                break;
            case 38:
                this.move(0, 5);
                break;
            case 39:
                this.move(5, 0);
                break;
            case 40:
                this.move(0, -5);
                break;
        }
    }
}

new Player()

Другие вопросы по тегам