javascript - XmlHttpRequest onload `this` 属性

标签 javascript

给定下面的代码,_onChunkComplete 方法中的this 是XHR 请求。这是有道理的。有没有办法让它成为实际的 Uploader 对象?

   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();

最佳答案

使用bind :

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

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

关于javascript - XmlHttpRequest onload `this` 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39153608/

相关文章:

javascript - 向服务器提交有序列表

javascript - 如果名称很长,如何使可点击按钮保持原位

javascript - Google Chart vAxis.format 大数字 10^30

javascript - jQuery AJAX 与普通表单的行为不同并在基于 div 的弹出窗口中调用

javascript - jQuery 将单个类与预定义列表进行匹配,其中元素具有多个类

javascript - 忽略 Webpack/Babel 的 .d.ts 文件?

javascript - 如何将 JSON 转换为索引数组

javascript - 为什么在创建对象之前使用 global.gc() 可以防止堆使用量出现负增量?

javascript - 如何使背景移动速度比 Skrollr 中的文本慢?

javascript - Promises polyfill 是否在 Google Closure Compiler 20161024 中包含 all()?