2012-07-09 66 views
1
Objekt.prototype.loadImg = function(pImg){ 
    if(pImg!=null){ 
     this.imgLoaded=false; 
     this.img = null; 
     this.img = new Image();   
     this.img.src = pImg;  
     this.img.onload = function(){ 
      alert("!"); 
      this.autoSize();     
      this.imgLoaded=true; 
     }; 

    } 
} 

我的問題是「this」在「onload = function()」函數中無效!Javascript圖像onload callback class-intern函數

alert(「!」);被執行,但不是Objekt.prototype.autoSize() - 例如函數!

我需要做些什麼來調用我的「class-intern」函數(例如autoSize)?

回答

1

這是因爲onload函數沒有被你的對象作爲接收者調用。因此,在此回調中,this不是所需的對象。

爲此,您可以發送thisonload回調:

Objekt.prototype.loadImg = function(pImg){ 
    if(pImg!=null){ 
     this.imgLoaded=false; 
     this.img = null; 
     this.img = new Image();   
     this.img.src = pImg;  
     var _this = this; 
     this.img.onload = function(){ 
      alert("!"); 
      _this.autoSize();     
      _this.imgLoaded=true; 
     }; 
    } 
} 
+0

完美!非常感謝你! – user1511417 2012-07-09 09:04:13