jQuery - 获取对此的引用

时间:2010-11-09 09:59:23

标签: javascript jquery

function Request(params)
{
    // Stuff stuff stuff

    // And then

    $.ajax(
    {
        type: 'GET',
        url: 'someurl',
        success: this.done
    });
}

Request.prototype.done = function()
{
    // "this" in this context will not refer to the Request instance.
    // How to reach it?
}

4 个答案:

答案 0 :(得分:4)

你可以先捕获“这个”:

function Request(params)
{
    // Stuff stuff stuff

    // And then

    var $this = this;

    $.ajax(
    {
        type: 'GET',
        url: 'someurl',
        success: function() { $this.done(); }
    });
}

答案 1 :(得分:3)

显然你可以将“context”参数添加到ajax请求中,如下所示:

$.ajax(
{
    type: 'GET',
    url: 'someurl',
    success: this.done,
    context: this
});

答案 2 :(得分:0)

this并不是指同一件事!!!“

答案 3 :(得分:-1)

尝试以下:

function Request(params)
{
   var that = this;

...

Request.prototype.done = function()
{
   that...