2009-08-31 42 views
0

给定一个实例化的JavaScript对象/类,我可以从该类进行Ajax调用,并将调用者的对象返回成功函数回调?获取Ajax调用返回到我的Javascript上下文

目前我可以得到回调返回回对象,但我失去了“这个”属性,它杀死了我的对象的状态

function BaseConsoleHelper() 
{ 
this._iconIndex = 0; 
} 
BaseConsoleHelper.prototype = { 
Dispose: function() 
{ 
this._previousIndex = 0; 
}, 
GetVisitConsoleIcons: function(name) 
{ 
    this._iconIndex = 500; 

    SampleNamespace.MyService.GetConsoleIcons(name, this.IconsGenerated); 
}, 
IconsGenerated : function(result) 
{ 
    //I should be 500.....but I'm not, cause "this" has become something else 
    alert(this._iconIndex); 
} 
}; 

BTW我使用asp.net AJAX 3.5(和,哇,是不是继承不同,这里比纯JavaScript)

回答

1

改变这一行:

SampleNamespace.MyService.GetConsoleIcons(name, this.IconsGenerated); 

到:

SampleNamespace.MyService.GetConsoleIcons(name, 
    Function.createDelegate(this, this.IconsGenerated) 
); 

有关在Web服务调用中保留对this的引用的更多示例,请参阅this article

+0

thx,刚刚发现了同样的事情。 后续问题:Function.createDelegate与Type.createDelegate? – BozoJoe 2009-09-01 00:45:19

+0

@Alex:他们是一样的(字面意思)。 MS AJAX别名'功能'为'类型',但正式你应该做'Function.createDelegate'而不是'Type.createDelegate'。 – JPot 2009-09-01 00:51:28