全局范围 - 在触发事件侦听器后访问“this”

时间:2013-10-22 10:20:17

标签: javascript mootools

我有一个使用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.bar方法中访问uploadComplete,但this

未传递xhr.addEventListener('load', this.uploadComplete, false);

感谢任何帮助。

1 个答案:

答案 0 :(得分: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 - 这会在事件触发时正确设置此上下文。

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