Javascript OOP - jQuery 在 ajax 请求中调用 "this"

标签 javascript jquery oop scope

我想发出一个仍然保留对当前对象的访问权限的 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);
                }
            });
        }
    }
}

关于Javascript OOP - jQuery 在 ajax 请求中调用 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9845639/

相关文章:

jquery - 水平居中对齐嵌套 ul li

JavaScript OOP 私有(private)变量

javascript - jquery 如何在点击时同时删除 <tr> 标签?

javascript - 使用 javascript 调整 Cycle2 的大小让事情变得紧张

javascript - Electron : Confirm and Alert of a website in a webview doesn't show

jquery - 使用 jquery 添加 html 元素

jquery - slider 高度技术

c# - 面向对象编程 : looking for good tutorials

oop - DDD - 补充骨料根的水分?

javascript - 使用表单时删除缓存的搜索