2009-08-31 22 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