0

So I am trying to create an object that holds another object inside of it when initialized. However, when I call a method in the outer object, it cannot find the inner object's variable.

class Game {

  constructor(){
    //creates canvas and ctx
    this.xPosition = 0
    this.yPosition = 0
    this.canvas = document.getElementById("canvas");
    this.canvas.style.background = "black";
    this.ctx = canvas.getContext("2d");
    this.drawSquare(0,0);
    this.snake = new Snake();
  }

  drawSquare(x,y){
    this.snake.head = [this.xPosition,this.yPosition];
    this.ctx.clearRect(this.xPosition, this.yPosition, 30, 30); //pop tail
    this.xPosition += x
    this.yPosition += y;
    if (this.xPosition < 0){
      this.xPosition = 600;
    }
    else if (this.xPosition > 600){
      this.xPosition = 0;
    }
    if (this.yPosition < 0){
      this.yPosition = 600;
    }
    else if (this.yPosition > 600){
      this.yPosition = 0;
    }
    this.ctx.fillStyle = "#FF0000";
    this.ctx.fillRect(this.xPosition,this.yPosition,30,30);
  }
}

class Snake {
  constructor(){
    this.head = [];
    this.tail = [];
    this.length = 1;
  }
}

When I run this code in the browser, I get an error: this.snake is undefined.

4
  • How do you call it? when getting the error Commented Jun 23, 2018 at 19:49
  • Before I even initialize an instance of Game, that is: var game = new Game(); I already get the error. Commented Jun 23, 2018 at 19:53
  • new Game() already throws an exception? what is the line of the code you are getting the exception? Commented Jun 23, 2018 at 19:56
  • the problem is with the line directly underneath the drawSquare method, this.snake.head = [this.xPosition,this.yPosition] Commented Jun 23, 2018 at 19:59

1 Answer 1

1

You are calling the method this.drawSquare that uses this.snake before initiating this.snake = new Snake()

Try replacing it on the constructor:

constructor(){
    //creates canvas and ctx
    this.xPosition = 0
    this.yPosition = 0
    this.canvas = document.getElementById("canvas");
    this.canvas.style.background = "black";
    this.ctx = canvas.getContext("2d");
    this.snake = new Snake();
    this.drawSquare(0,0); // this line changed
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.