2012-07-09 58 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