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

时间:2018-06-23 19:47:00

标签: javascript oop

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

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 :(得分:1)

在启动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
  }