Javascript jqueryajax:传递范围以设置它
我有一个ajax调用的类: 人=功能(){ 在ajax调用成功时,我想设置person的当前实例,但“this”的设置范围不正确。 有比使用全局变量更优雅的方法吗Javascript jqueryajax:传递范围以设置它,javascript,ajax,jquery,Javascript,Ajax,Jquery,我有一个ajax调用的类: 人=功能(){ 在ajax调用成功时,我想设置person的当前实例,但“this”的设置范围不正确。 有比使用全局变量更优雅的方法吗 提前感谢您的帮助,我为我的英语不好道歉。您不需要全球英语培训 只要说: var self = this; 紧靠返回$.ajax(…)行之前,然后使用self在ajax回调函数中引用当前实例 此变量仅在GetById()函数的作用域内。当然,您可以将This放入变量,然后在回调中使用该变量 var self = this; thi
提前感谢您的帮助,我为我的英语不好道歉。您不需要全球英语培训 只要说:
var self = this;
紧靠返回$.ajax(…)
行之前,然后使用self
在ajax回调函数中引用当前实例
此变量仅在
GetById()
函数的作用域内。当然,您可以将This
放入变量,然后在回调中使用该变量
var self = this;
this.GetById = function (id) {
return $.ajax({
type: "POST",
url: "/Services/PersonService.svc/GetPersonById",
data: JSON.stringify(id),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
...
self = data;
...
}
});
}
该方法为您提供了一个context
属性,您可以在其中设置回调中this
的值
只要做:
context: this,
…在您的通话中,例如:
this.GetById = function (id) {
return $.ajax({
type: "POST",
context: this, // <---- context property to set "this" in the callbacks
url: "/Services/PersonService.svc/GetPersonById",
data: JSON.stringify(id),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// in here, "this" will be the same as in your "getById" method
}
});
}
this.GetById=函数(id){
返回$.ajax({
类型:“POST”,
上下文:这,//不,可能不是self=data
,因为这只会覆盖前面的“self”值。更像是self.something=data
或self.something(data)
对吗?@Pointy确实,覆盖self
会得到一个没有任何附加方法的普通对象,并且无论如何也不会改变这个
。确实,你们是对的。在这种情况下,我假设没有方法的数据将与此相同。正确的解决方案将如Pointy所说。然后我们需要知道callback函数参数数据,使用闭合隔膜“that”给出问题的工作解决方案,而不是person的当前实例。我在Patrick的帮助下完成了我的目标。此外,使用Jquery.extend还可以防止您覆盖我的类中的函数。尽管您的范围有问题,但您不能覆盖此
this.GetById = function (id) {
return $.ajax({
type: "POST",
context: this, // <---- context property to set "this" in the callbacks
url: "/Services/PersonService.svc/GetPersonById",
data: JSON.stringify(id),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// in here, "this" will be the same as in your "getById" method
}
});
}