我有一个使用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);
感谢任何帮助。
答案 0 :(得分:4)
您需要使用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);