【问题标题】:variables not reachable in prototype-methods [duplicate]原型方法中无法访问的变量[重复]
【发布时间】:2015-07-02 14:21:11
【问题描述】:

我无法在 Class 的任何原型方法中访问我在 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>

【问题讨论】:

标签: javascript prototype-programming


【解决方案1】:

这是因为上下文。 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);
};
// ...

【讨论】:

    【解决方案2】:

    这一行正在改变你的上下文。

    this.request.onProgress = this.onProgress
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 2016-06-22
      • 1970-01-01
      • 2017-03-31
      相关资源
      最近更新 更多