我从 javascript 对象内部进行一些 Ajax 调用:
myObject.prototye = {
ajax: function() {
this.foo = 1;
var req = new XMLHttpRequest();
req.open('GET', url, true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200) {
alert(this.foo); // reference to this is lost
}
}
}
};
在 onreadystatechange 函数内部,this 不再引用主对象,因此我无权访问 this.foo。如何在 XMLHttpRequest 事件中保留对主对象的引用?
最简单的方法通常是存储this
在局部变量上:
myObject.prototype = {
ajax: function (url) { // (url argument missing ?)
var instance = this; // <-- store reference to the `this` value
this.foo = 1;
var req = new XMLHttpRequest();
req.open('GET', url, true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if (req.status == 200) {
alert(instance.foo); // <-- use the reference
}
}
};
}
};
我还怀疑你的myObject
标识符实际上是一个构造函数(您正在分配一个prototype
财产)。
如果是这种情况,请不要忘记添加正确的constructor
属性(因为您要替换整个prototype
),这只是对构造函数的引用。
可能与这个问题无关,但建议阅读:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)