首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XmlHttpRequest onload ` `this`‘属性

XmlHttpRequest onload ` `this`‘属性
EN

Stack Overflow用户
提问于 2016-08-25 19:47:57
回答 2查看 265关注 0票数 1

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

代码语言:javascript
复制
   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();
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-25 19:52:57

使用bind

代码语言:javascript
复制
this.upload_request.onload = this._onChunkComplete.bind(Uploader)

bind()方法创建一个新函数,当调用该函数时,它的this关键字设置为提供的值,在调用新函数时,在任何提供的参数之前都有给定的参数序列。

票数 2
EN

Stack Overflow用户

发布于 2016-08-25 19:52:02

只需通过参数将Uploader对象传递给函数:

代码语言:javascript
复制
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...
};

但是,如果您想要通过this对象重写uploader,那么Martriay的答案就是正确的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39153608

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档