2

我有一个使用 XHR 上传文件的 mootools 类:

var foo = new Class({

    initialize: function() {

        this.bar = 'value';
    },

    upload: function() {

        // This method uploads a file

        ….
        xhr.addEventListener('load', this.uploadComplete, false);
        ….

    },
    uploadComplete: function() {

        // Is getting called on completion of file upload       

        console.log(this.bar); // undefined, but I want to to be 'value'
    }


});

我想访问this.baruploadComplete方法,但this没有通过xhr.addEventListener('load', this.uploadComplete, false);

任何帮助表示赞赏。

4

1 回答 1

4

您需要使用Function.prototype.bind- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bindhttp://mootools.net/docs/core/Types/Function#Function :bind - 当事件触发时,它将正确设置 this 的上下文。

xhr.addEventListener('load', this.uploadComplete.bind(this), false);

于 2013-10-22T10:23:57.697 回答