0

I wrote some code for a class called Player, which initializes some attributes upon usage. One of the attributes is an array. Here's my simplified code:

class Player {
    constructor(basicStuff) {
        this.basicStuff = basicStuff
        this.keys = [];
    }
    move(event) {
        this.keys[event.key] = true;
        //moves position
    }
    releaseKey(event) {
        //updates the keys pressed
    }
    draw(scene) {
        //draws player
    }
}

const player = new Player("basicStuff");
window.addEventListener('keydown', player.move);
window.addEventListener("keyup", player.releaseKey);

So here's the problem: when I run the code and test it, I would get "Uncaught TypeError: Cannot set property 'event.key' of undefined". It seems like this.keys from the const player was never defined even though it's very clear that I've done so in the constructor. What should I do so this.keys in the move method of player is not undefined?

Note: This piece of Javascript code is cooperating with another Node.js file, if that's helpful to mention.

  • Did you mean to use an object instead of an array? `this.keys = {};` – elclanrs Apr 12 '20 at 02:18
  • You have to bind the event listeners to the player: https://reactjs.org/docs/handling-events.html – xehpuk Apr 12 '20 at 02:22
  • The `this` inside `move` will refer to the global window object since JS handles the execution of the function, not the object instance. You could bind the this in your constructor using `this.move = this.move.bind(this)` – Nick Parsons Apr 12 '20 at 02:22
  • `window.addEventListener('keydown', player.move.bind(player));` otherwise the method is just a function that ignore which object it is linked to – Mister Jojo Apr 12 '20 at 02:26
  • So I added multiple bindings similar to "this.move = this.move.bind(this)" but then I get the error "Uncaught TypeError: Cannot read property 'bind' of undefined". It highlights the second method I tried to bind. Even when I only bind the first method, I get "TypeError: chrome[I51][b51][o01[A61]] is not a function". – Dysrakescence Apr 12 '20 at 03:01
  • Edit: Thanks everyone, I tried all the methods I could find and Mister Jojo's approach was the only one that could solve my problem. Thanks again! – Dysrakescence Apr 12 '20 at 03:56

0 Answers0