对象内的XMLHttpRequest:如何保持对“this”的引用 [英] XMLHttpRequest inside an object: how to keep the reference to "this"
问题描述
我在javascript对象中进行了一些Ajax调用。:
I make some Ajax calls from inside a javascript object.:
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.foo。我可以在XMLHttpRequest事件中保留对主对象的引用吗?
Inside the onreadystatechange function, this does not refer to the main object anymore, so I don't have access to this.foo. Ho can I keep the reference to the main object inside XMLHttpRequest events?
推荐答案
最简单的方法通常是存储值本地变量上的
:
The most simple approach is usually to store the value of this
on a local variable:
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
标识符是真的是一个构造函数(你指的是原型
属性)。
I suspect also that your myObject
identifier is really a constructor function (you are assigning a prototype
property).
如果是这种情况,请不要忘记包含正确的构造函数
property(因为你要替换整个 prototype
),这只是一个回到构造函数的引用。
If that's the case don't forget to include the right constructor
property (since you are replacing the entire prototype
), which is simply a reference back to the constructor.
也许这个问题偏离主题,但建议阅读:
Maybe off-topic to this issue but recommended to read:
- Constructors considered mildly confusing
这篇关于对象内的XMLHttpRequest:如何保持对“this”的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!