我想訪問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
爲什麼我們可以直接訪問自變量?在onload函數中是不是作用域等於img對象? – mallaudin
不,'onload'從全局範圍運行,因爲它本質上是觸發事件的'window'對象。嘗試在onload中執行'console.log(this)',你會看到。 –
那麼你如何從全局範圍訪問局部變量self?困惑.. – mallaudin