【问题标题】:Getting an Ajax call to return into my Javascript context获取 Ajax 调用以返回到我的 Javascript 上下文
【发布时间】:2009-08-31 23:50:27
【问题描述】:

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

目前我可以让回调返回到对象中,但是我丢失了“this”属性,这会杀死我的对象的状态

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 );
}
};

顺便说一句,我使用 asp.net ajax 3.5(哇,这里的继承与纯 JavaScript 没有什么不同)

【问题讨论】:

    标签: asp.net javascript asp.net-ajax


    【解决方案1】:

    改变这一行:

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

    到:

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

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

    【讨论】:

    • 谢谢,刚刚发现了同样的事情。后续问题:Function.createDelegate vs. Type.createDelegate?
    • @Alex:它们是一回事(字面意思)。 MS AJAX 将 Function 别名为 Type,但官方应该使用 Function.createDelegate 而不是 Type.createDelegate
    猜你喜欢
    • 2012-11-20
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 2012-03-29
    相关资源
    最近更新 更多