变量在原型方法中无法访问

时间:2015-07-02 14:21:11

标签: javascript prototype-programming

我无法在类的任何原型方法中找到我在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 个答案:

答案 0 :(得分: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);
};
// ...

答案 1 :(得分:0)

这一行正在改变你的背景。

this.request.onProgress = this.onProgress

基本上这里发生的是this.request.onProgress被触发,并引用this.onProgress。 onProgress函数中的“this”成为this.request对象。