簡體   English   中英

如何從javascript中的父對象引用變量

[英]how to reference a variable from the parent object in javascript

我正在嘗試編寫一個簡單的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM