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

how to reference a variable from the parent object in javascript

本文关键字:对象 变量 引用 javascript      更新时间:2023-11-11

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

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对象中的变量?

声明一个变量:

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

或者绑定你的函数(我在这里不会这么做,因为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