-3

I am creating a game in javascript. When user clicks UP arrow it launches a missile. User should be able to click the UP arrow and each click should launch a new missile. I have a 'missile' object and an array of 'missile's. Missile object has a launch function.

The below line gives me an error when used inside setInterval. It works without issue when I comment out the setInterval.

Error message: game.js:21

Uncaught TypeError: Cannot read property 'style' of undefined at game.js:21

Line with error: this.image.style.left=this.leftPos+'px';

var missile = {
    leftPos: 0,
    bottomPos: 0,
    image: null,
    id: null,
    launch: function () {
        setInterval(function () {
            this.image.style.left = this.leftPos + 'px';
            this.image.style.bottom = this.bottomPos + 'px';
            this.leftPos += 0.5;
            this.bottomPos += 1;
        }, 10);
    }
}; 

Somewhere down I call this: currMissile=missiles[missiles.length-1]; currMissile.launch();

  • ‘this’ is not what you think it is. The function supplied to setInterval is not executed on the same object context. Search for “javascript self this” or “javascript bind”. – user2864740 Nov 25 '18 at 02:12
  • See also: https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – Mark Nov 25 '18 at 02:14

1 Answers1

0

The context this is not referencing to the object missile, further, I can see you're filling an array with the same object multiple times, this means all indexes in the array are pointing to the same object which relies on errors.

You should instantiate a new object every time the user presses UP.

For example

var Missile = function() {
  this.leftPos = 0;
  this.bottomPos = 0;
  this.image = { // Example
    style: {
      left: 4,
      bottom: 34
    }
  };
  this.id = null;
  this.launch = function() {
    setInterval(() => { // Use arrow function to get access to Missile lexical context.
      this.image.style.left = this.leftPos + 'px';
      this.image.style.bottom = this.bottomPos + 'px';
      this.leftPos += 0.5;
      this.bottomPos += 1;
      console.log(this.image.style.left);
    }, 500);
  };
};

new Missile().launch();
.as-console-wrapper { max-height: 100% !important; top: 0; }
Ele
  • 33,468
  • 7
  • 37
  • 75