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

Global scope - access "this" after firing event listener

本文关键字:访问 this 侦听器 事件 范围 全局      更新时间:2023-09-26

我有一个使用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'
    }

});

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

任何帮助,不胜感激。

您需要

使用 Function.prototype.bind - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind 和 http://mootools.net/docs/core/Types/Function#Function:bind - 这将在事件触发时正确设置上下文。

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