Итак, я пытаюсь создать объект, который содержит другой объект внутри него при инициализации. Однако, когда я вызываю метод во внешнем объекте, он не может найти переменную внутреннего объекта.
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 не определен .