代码之家  ›  专栏  ›  技术社区  ›  beingalex

全局作用域-在触发事件侦听器后访问“this”

  •  2
  • beingalex  · 技术社区  · 11 年前

    我有一个使用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 回复  |  直到 11 年前
        1
  •  4
  •   Dimitar Christoff    11 年前

    你需要使用 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);