2015-07-02 118 views
1

我不能達到我在我的ImageLoaderClass在類的任何原型法的構造方法聲明的變量不可達:變量原型方法

<div id="progress" ></div> 
<a href="javascript:start();">Test</a> 
<script> 
function ImageLoader (url,ziel){ 
    this.url = url; 
    this.ziel=ziel; 
    this.request = new XMLHttpRequest(); 
    this.request.onprogress = this.onProgress; 
    this.request.onload = this.onComplete; 
    this.request.onerror = this.onError; 
    this.request.open('GET', this.url, true); 
    this.request.overrideMimeType('text/plain; charset=x-user-defined'); 
    this.request.send(null); 
} 
ImageLoader.prototype.onProgress=function(event) { 
    if (!event.lengthComputable) { 
    return; 
    } 
    alert("url="+this.url); 
    this.loaded = event.loaded; 
    this.total = event.total; 
    this.progress = (this.loaded/this.total).toFixed(2); 
    document.querySelector('#progress').textContent = 'Loading... ' + parseInt(this.progress * 100) + ' %'; 
} 
ImageLoader.prototype.onComplete=function(event) { 
    alert(this.url); 
    document.querySelector('#progress').setAttribute('src', this.url); 
    console.log('complete', this.url); 
} 

ImageLoader.prototype.onError=function(event) { 
    console.log('error'); 
} 

function start(){ 
    //var request = new XMLHttpRequest(); 
    var Fab=new ImageLoader('https://placekitten.com/g/2000/2000','#progress'); 
} 
</script> 
+2

JavaScript中的'this'不能像其他語言一樣工作。看看這個答案,以解釋如何'這'在js工作:http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-文字/ 13441628#13441628 – slebetman

回答

2

這是因爲上下文。 this不是你想象的那個。

只需綁定正確的上下文,或者包裝你的函數綁定。

this.request.onprogress = this.onProgress.bind(this); 
this.request.onload = this.onComplete.bind(this); 
this.request.onerror = this.onError.bind(this); 

或者

var that = this; 
this.request.onprogress = function(event){ 
    that.onProgress(event); 
}; 
// ... 
0

此行是改變你的這種情況下。

this.request.onProgress = this.onProgress 

基本上這裏發生的事情是this.request.onProgress被觸發,並引用this.onProgress。 onProgress函數中的「this」變爲this.request對象。