Javascript OOP-jQuery调用;这个“;ajax请求内部

Javascript OOP - jQuery calling "this" inside ajax request

本文关键字:ajax 请求 内部 这个 OOP-jQuery 调用 Javascript      更新时间:2023-09-26

我想发出一个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);
                }
            });
        }
    }
}

救援关闭:

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