1

I am trying to learn relationship between classes and listeners in javascript. I want to make listener change the properties of an object. I am also trying to use modular code. My class code is:

export class Game{
    constructor(){
        this.prop = 1;
        document.onkeydown = this.initListeners;
    }

    initListeners(e){
        if (e.keyCode == '37') {
            this.prop = 5;
            console.log("Current: " + this.prop);
        }
    }

    play(){
        console.log("Playing: " + this.prop);
        setTimeout(()  => { 
            this.play();
        }, 300);
    }
}

During construction, it sets the prop property to 1 and it sets the listener so that when the left arrow key is pressed, it sets the prop property of object to 5. play() method just prints the property recursively. My app.js (which is included in html) code looks like:

import {Game} from "./game.js";

var game = new Game();
game.play();

So the desired output is, at first it should print 1 and after pressing the left arrow key, it should start printing 5. But instead, when pressed, it prints Current: 5 but then continues to print: Playing: 1. What is the problem? and how can I solve it?

Giorgi Cercvadze
  • 403
  • 1
  • 7
  • 23

0 Answers0