Javascript 来自对象的内部ajax调用正在清除成员变量
我有目标Javascript 来自对象的内部ajax调用正在清除成员变量,javascript,ajax,oop,Javascript,Ajax,Oop,我有目标 var MyObject = (function (){ var MyObject = function (a,b){ this.A = a; this.B = b; this.C; } MyObject.prototype.PublicFunction = function(){ var someVariable = 123; //this.A and this.B
var MyObject = (function (){
var MyObject = function (a,b){
this.A = a;
this.B = b;
this.C;
}
MyObject.prototype.PublicFunction = function(){
var someVariable = 123; //this.A and this.B are both fine here.
var self = this;
$.ajax({
type: "POST",
url: "Default.aspx/PageMethod",
data: "{" + args + "}",
dataType: "json",
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
//this.A = undefined, this.B = undefined, this.C = the data.
self.C = data.d
},
error: function(xhr, status, error){
alert('tears');
}
});
}
return MyObject;
}());
当我输入原型函数
时,这个.A\B
都是来自构造函数的值。执行ajax调用后,这两个.A\B
都是未定义的。我不知道该怎么办。我可能不理解我需要理解的对象中的范围。有人能帮忙吗?与您前面的问题类似,您的成功函数很可能在没有上下文的情况下执行(因此它是在全局上下文中,其中this==window
)
只需尝试将this
(console.log(this)
)记录到success函数中-您将看到它是窗口
对象
对于您遇到的问题,一个常见的解决方法是创建一个对该
的本地引用,如下所示:
MyObject.prototype.PublicFunction = function(){
var self = this;
var someVariable = 123; //this.A and this.B are both fine here.
//AJAX HOOPLAH
Success(data) {
self.C = data.d
//this.A = undefined, this.B = undefined, this.C = the data.
}
Fail{
alert('tears');
}
}
您可以包含更多ajax hooplah吗?您可以将success函数绑定到this
<代码>函数(数据){…}.bind(this)
由于聊天系统中的讨论:这需要在IE6+上得到支持,因此.bind将不起作用,整个.prototype也可能不起作用。如果IE6/7支持扩展.prototype,我就忘了