2016-08-25 2 views
1

_onChunkCompleteメソッド内のthisメソッドは、XHRリクエストです。どちらが理にかなっている。それを実際のUploaderオブジェクトにする方法はありますか?XmlHttpRequest onload `this`プロパティ

function Uploader(file, options) {  
     // ... code here .... 
     this.upload_request = new XMLHttpRequest(); 
     this.upload_request.onload = this._onChunkComplete; 
    } 

    Uploader.prototype = { 
     // ... code here ... 
     _onChunkComplete: function() { 
      if (this.range_end === this.file_size) { 
       console.log('done'); 
       return; 
      } 
      this.range_start = this.range_end; 
      this.range_end = this.range_start + this.chunk_size; 
      if (!this.is_paused) { 
       this._upload(); 
      } 
     } 
     // ... mode code here... 
    }; 

    var test = new Uploader(formFile, {}); 
    test.start(); 

答えて

2

使用bind

this.upload_request.onload = this._onChunkComplete.bind(Uploader) 

バインド()メソッドが呼び出されたとき、その このキーワードは、任意の前 引数の指定された配列と、与えられた値に設定されている、新たな機能を作成します新しい関数が呼び出されたときに提供されます。

+0

どのように私はこれについて知らなかった... 私は '.bind(本)でした'と、それは完璧に動作します。ありがとうございました。 – Charlie

0

ちょうどパラメータで関数にUploaderオブジェクトを渡す:

Uploader.prototype = { 
    // ... code here ... 

    var uploader = this; 

    _onChunkComplete: function(uploader) { 

     // you can use uploader now 

     if (this.range_end === this.file_size) { 
      console.log('done'); 
      return; 
     } 
     this.range_start = this.range_end; 
     this.range_end = this.range_start + this.chunk_size; 
     if (!this.is_paused) { 
      this._upload(); 
     } 
    } 
    // ... mode code here... 
}; 

をしかし、あなたはthisuploaderによってオブジェクトを上書きしたい場合は、Martriayの答えはちょうどいいです。