如何在javascript中引用父对象的变量

时间:2013-11-26 14:31:59

标签: javascript image canvas

我正在尝试编写一个简单的精灵对象,它会在初始化时将自己添加到画布中:

function Sprite(source){
this.x = 100;
this.y = 100;
this.img = new Image();
this.img.src = source;
this.img.onload = function(e){
    context.drawImage(this.img, this.x, this.y);
    };
}//end of object Sprite

这不起作用,因为drawImage需要访问onload处理程序之外的变量。如何从事件处理程序中访问我的Sprite对象中的变量?

1 个答案:

答案 0 :(得分:0)

声明变量:

function Sprite(source){
  var sprite = this;
  this.x = 100;
  this.y = 100;
  this.img = new Image();
  this.img.src = source;
  this.img.onload = function(e){
    context.drawImage(this, sprite.x, sprite.y);
  };
}//end of object Sprite

bind你的函数(我不会这样做,因为onload事件处理程序应该绑定到相关的图像上):

function Sprite(source){
  this.x = 100;
  this.y = 100;
  this.img = new Image();
  this.img.src = source;
  this.img.onload = (function(e){
    context.drawImage(this.img, this.x, this.y);
  }).bind(this);
}//end of object Sprite