0

So I am pretty new to JavaScript, and I recently stumbled upon the fact that JavaScript has a more modern way of creating classes similar to Java and C#. I thought I consider learning some JavaScript because of this. Right now I am realizing that there are subtle differences between JS and Java/C#, and this issue I now have seems to be one.

Below, I defined a class called Game to act as a global object for a game I am trying to create.

    class Game
    {

        constructor(canvas, ctx)
        {
             this.canvas = canvas;
             this.ctx = ctx;

             this.screenManager = new ScreenManager();
             // initialization of more objects
        }

        run()
        {
            setInterval(function(){
                this.screenManager.updateScreen();
                this.screenManager.drawScreen(this.ctx);
            },15);
        }

    }

The issue I seem to be having is that after I call the constructor within my Game class, this.screenManager is left as undefined. I am noticing that the constructor of my Game class doesn't initialize objects declared in that class.

Now I do know that JavaScript runs code asynchronously, but not really sure if that fact plays into effect. With this said, what is the reasoning behind this declaration error, and what can be done to combat this issue.

PS: If you could try to write JS classes without prototyping, that would most definitely be appreciated! Thanks.

user3750761
  • 27
  • 1
  • 1
  • 8
  • Since you're using ES2015, the simplest solution in the linked dupetarget is an arrow function: `setInterval(() => { this.screenManager.updateScreen(); this.screenManager.drawScreen(this.ctx); }, 15);` – T.J. Crowder Nov 11 '16 at 11:52
  • Separately: Perhaps consider [`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) rather than trying to use a 15ms interval timer to emulate what the browser's already doing. :-) – T.J. Crowder Nov 11 '16 at 11:54

0 Answers0