1

I can't reach the variables I've declared in the constructor method of my ImageLoaderClass in any prototype method of the Class:

<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>
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
  • 2
    `this` in javascript doesn't work like in other languages. Check out this answer for an explanation of how `this` works in js: http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628 – slebetman Jul 02 '15 at 14:36

2 Answers2

2

This is because of the context. The this is not the one you think.

Just bind the correct context, or wrap your functions bindings.

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

Or

var that = this;
this.request.onprogress = function(event){
    that.onProgress(event);
};
// ...
mguimard
  • 1,881
  • 13
  • 14
0

This line is changing your context of this.

this.request.onProgress = this.onProgress

Essentially what's happening here is that this.request.onProgress is fired, and references this.onProgress. The "this" in the onProgress function becomes the this.request object.

Brodie
  • 8,399
  • 8
  • 35
  • 55