JavaScript:无法访问嵌套对象中的变量

JavaScript:无法访问嵌套对象中的变量,javascript,oop,Javascript,Oop,因此,我试图创建一个对象,当初始化时,该对象中包含另一个对象。但是,当我在外部对象中调用方法时,它找不到内部对象的变量 class Game { constructor(){ //creates canvas and ctx this.xPosition = 0 this.yPosition = 0 this.canvas = document.getElementById("canvas"); this.canvas.style.backgroun

因此,我试图创建一个对象,当初始化时,该对象中包含另一个对象。但是,当我在外部对象中调用方法时,它找不到内部对象的变量

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未定义。

在启动this.snake=new snake之前,您正在调用使用this.snake的this.drawSquare方法

尝试在构造函数上替换它:

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
  }

你怎么称呼它?在我初始化游戏实例之前得到错误时,即:var Game=new Game;我已经得到了错误。新游戏已经抛出了异常?得到异常的代码行是什么?问题在于drawSquare方法正下方的行this.snake.head=[this.xPosition,this.yPosition]