JavaScript: не может получить доступ к переменной внутри вложенных объектов - PullRequest
0 голосов
/ 23 июня 2018

Итак, я пытаюсь создать объект, который содержит другой объект внутри него при инициализации. Однако, когда я вызываю метод во внешнем объекте, он не может найти переменную внутреннего объекта.

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;
  }
}

Когда я запускаю этот код в браузере, я получаю сообщение об ошибке: this.snake не определен .

1 Ответ

0 голосов
/ 23 июня 2018

Вы вызываете метод this.drawSquare, который использует this.snake перед инициацией this.snake = new Snake()

Попробуйте заменить его на конструкторе:

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
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...