Javascript OOP - jQuery, вызывающий this в запросе ajax - PullRequest
3 голосов
/ 23 марта 2012

Я хотел бы сделать ajax-запрос, который по-прежнему сохраняет доступ к текущему объекту.Кто-нибудь знает, возможно ли это?

Пример того, что я хотел бы сделать:

function mobile_as(as_object, inputID) {
    this.object = 'something';
    if (as_object) this.object = as_object;
    this.inputID = inputID;

    // Get results for later usage.
    this.get_results = function(value) {
            this.request = $.getJSON("URL", { as: this.object }, function (data) {
                // Scope of "this" is lost since this function is triggered later on.
                if (data['status'] == "OK") {
                    alert(this.inputID);
                }
            });
        }
    }
}

1 Ответ

10 голосов
/ 23 марта 2012

Закрытие на помощь:

function mobile_as(as_object, inputID) {
    var self = this; // <---------
    this.object = 'something';
    if (as_object) this.object = as_object;
    this.inputID = inputID;

    // Get results for later usage.
    this.get_results = function(value) {
            this.request = $.getJSON("URL", { as: this.object }, function (data) {
                // Scope of "this" is lost since this function is triggered later on.
                self.... //self is the old this
                if (data['status'] == "OK") {
                    alert(self.inputID);
                }
            });
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...