Javascript 类 属性 未读

Javascript Classes Property not being read


没有读取属性 x,y,width,height!当我做.drawImage()时,this.x, this.y, this.width, this.height没有被使用!

假设我改变了 x 图像不会改变它的位置。但是,如果我 alert(this.x) 或任何变量,那么它将打印出正确的值。

感谢社区的帮助!

var Enemy = function(word, x, y, width, height) {

  this.word = word;

  //Position of the Enemy Spawn
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}
Enemy.prototype.draw = function() {
  var image = new Image();
  image.onload = function() {
    Context.context.drawImage(image, this.x, this.y, this.width, this.height)
  };
  image.src = "enemy.png"
  // If I do alert(this.x), it returns the correct value!!!
}

这是初始化:

var myEnemy = new Enemy("TestEnemy", 100, 100, 100, 100);
myEnemy.draw();

您的问题与您使用 this 的方式有关。您在 image.onload = function() 中引用 this.x。由于 this 在当前执行上下文中解析,在这种情况下 this 将引用正在加载的图像。由于您需要将 this 引用为 Enemy,因此您可以创建一个变量引用来维护 Enemy:

的上下文
Enemy.prototype.draw = function(){
  var image = new Image();
  var self = this;
  image.onload = function() {
    Context.context.drawImage(image, self.x, self.y, self.width, self.height);
  };
  image.src = "enemy.png";
}

当您执行 alert(this.x) 时,您将获得正确的值,因为您调用它的范围是正确的。要查看实际效果,请添加以下代码并在浏览器开发工具中查看结果:

var self = this;
image.onload = function() {
  console.log(this);
  console.log(self);
}  

image.onload事件下的上下文在图像下,而不是 Enemy 的实例。

为了访问 x、y、宽度和高度,您需要将实例存储到某个变量,例如:

Enemy.prototype.draw = function() {
  var image = new Image();
  var self = this;
  image.onload = function() {
    Context.context.drawImage(image, self.x, self.y, self.width, self.height);
  };
  image.src = "enemy.png";    
}