2015-05-04 49 views
0

我想訪問onload函數中的img屬性我該怎麼做?我將img屬性添加到Picture對象,並調用onload函數的範圍爲Picture對象,但我仍無法訪問this.img。使用Object.call訪問父範圍

// picture 
    function Picture(x, y, w, h, imgurl){ 
     this.x = x; 
     this.y = y; 
     this.w = w; 
     this.h = h; 
     this.imgurl = imgurl; 
     this.draw = drawPic; 
     this.overcheck = overRect; 
    } // end picture 

    function drawPic(){ 
      this.img = new Image(); // add img to this scope 
      this.img.src = this.imgurl; 
      this.img.onload = function(){ 
       //ctx.drawImage(this.image, this.that.x, this.that.y, this.that.w, this.that.h); 
       ctx.drawImage(this.img, this.x, this.y, this.w, this.h); //error 
      } // end onload 
      this.img.onload.call(this); 
    } // end drawPic 

回答

1

使用this

function drawPic() { 
    var self = this; 
    this.img = new Image(); 
    this.img.src = this.imgurl; 
    this.img.onload = function() { 
    ctx.drawImage(self.img, self.x, self.y, self.w, self.h); 
    }; 
} 
+0

爲什麼我們可以直接訪問自變量?在onload函數中是不是作用域等於img對象? – mallaudin

+0

不,'onload'從全局範圍運行,因爲它本質上是觸發事件的'window'對象。嘗試在onload中執行'console.log(this)',你會看到。 –

+0

那麼你如何從全局範圍訪問局部變量self?困惑.. – mallaudin

0

參考我認爲你必須定義對象內部的功能:

function Picture(x, y, w, h, imgurl){ 
    this.x = x; 
    this.y = y; 
    this.w = w; 
    this.h = h; 
    this.imgurl = imgurl; 
    this.draw = function(){ 
     this.img = new Image(); // add img to this scope 
     this.img.src = this.imgurl; 
     this.img.onload = function(){ 
      ctx.drawImage(this.img, this.x, this.y, this.w, this.h); //error 
     } // end onload 
     this.img.onload.call(this); 
    } // end drawPic; 

    this.overcheck = overRect; 
} // end picture 
+0

這將爲每個新圖片對象創建一個新的函數對象。 – mallaudin

+0

@mallaudin嗯,好點 –

+1

如果你想採取該路線,你可以在原型上定義它:'Picture.prototype.draw = function(){...} –