0

I am trying to write a simple snake game and I am learning JavaScript as I do so. I have a separate file for my Snake class that I want the main file to use. The problem is that I have declared several variables at the top of the class to use in my functions but they are a hit or miss.

function Snake() {
  this.move_y = 0;
  this.move_x = 0;
  this.height = 50;
  this.width = 50;
  this.speed = 20;

  this.moveRight = function() {
    this.speed = 20;
    console.log(this.move_x); //Outputs 0
    this.move_x += this.speed;
    console.log(this.speed); //Outputs 20

    //document.getElementById("head").style.left = this.move_x + "px";
  }

  this.moveDown = function() {
    this.speed = 20;
    console.log(this.move_y); //Outputs "Undefined"
    this.move_y += this.speed;
    console.log(this.move_y); //Outputs "NaN"

    //document.getElementById("head").style.top = this.move_y + "px";
  }
}

var dangerNoodle = new Snake();
dangerNoodle.moveRight();
dangerNoodle.moveDown();

This is the file that I am using that utilizes the class:

"use strict";

var move_x = 0;
var speed_x = 0;
var repeat;
var snakeHead = document.getElementById("head");
var snake;

window.onload = setUp;

function setUp()
{
    snake = new Snake();

    snakeHead.style.width = snake.width + "px";
    snakeHead.style.height = snake.height + "px";

    document.onkeydown = move;
}

function move(e)
{
    if (e.keyCode == 39)
    {
      clearInterval(repeat);
      repeat = setInterval(snake.moveRight, 1000);
    }
    else if (e.keyCode == 40)
    {
      clearInterval(repeat);
      repeat = setInterval(snake.moveDown, 1000);
    }
}

Why is it that my move_x variable works as intended but my move_y variable does not?

  • they both behave as you expect in code snippet – Mhmdrz_A Feb 29 '20 at 08:59
  • 1
    `this` in your "move" functions is the global object. `move_x` works because there's a global `move_x` but not `move_y` -> [How does the “this” keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) + [How to access the correct `this` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Andreas Feb 29 '20 at 09:10

0 Answers0