在javascript原型addEventListener中使用此关键字
我想在事件侦听器函数中使用此关键字在javascript原型addEventListener中使用此关键字,javascript,jquery,xmlhttprequest,Javascript,Jquery,Xmlhttprequest,我想在事件侦听器函数中使用此关键字 var MyViewModel = function (file) { this.status = ""; this.xm = new XMLHttpRequest(); this.xm.addEventListener("load", this.onLoad, false); }; MyViewModel.prototype.onLoad = function (e) { this.status = "ok"; }
var MyViewModel = function (file) {
this.status = "";
this.xm = new XMLHttpRequest();
this.xm.addEventListener("load", this.onLoad, false);
};
MyViewModel.prototype.onLoad = function (e) {
this.status = "ok";
};
在onLoad prototype中,我无法访问带有此关键字的对象
- 此对象是窗口
- e参数是XmlHttpRequest
我如何访问它?您可以使用jQuery.proxy解决这个问题 这是在指定函数范围
var MyViewModel = function (file) {
this.status = "";
this.xm = new XMLHttpRequest();
this.xm.addEventListener("load", $.proxy(this.onLoad, this), false);
};
MyViewModel.prototype.onLoad = function (e) {
this.status = "ok";
};
现在,您可以将此关键字用作MyViewModel。没有jQuery,您还可以执行以下操作:
function MyViewModel(file) {
this.status = "";
this.xm = new XMLHttpRequest();
var viewModel = this;
this.xm.addEventListener("load", function(){viewModel.onLoad()}, false);
}
因此,对实例的引用使用viewModel保存在闭包中,然后用于将其设置为调用中所需的值。
此
应为xm
对象?您无法访问静态方法中的对象。将onLoad
改为私有方法。可能重复的