Search code examples
javascriptprototype-programming

variables not reachable in prototype-methods


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>

Solution

  • 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);
    };
    // ...