Fmak
Fmak

Reputation: 1

JavaScript: cannot access variable within nested objects

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.

Upvotes: 0

Views: 46

Answers (1)

Daniel Krom
Daniel Krom

Reputation: 10058

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
  }

Upvotes: 1

Related Questions