【问题标题】:JavaScript & jQuery: Calling inner functions [duplicate]JavaScript 和 jQuery:调用内部函数
【发布时间】:2013-04-06 11:10:21
【问题描述】:

我在 JavaScript 和 jQuery 中有以下代码以及集成的 ajax 请求。 问题:为什么可以调用内部函数success1(),但不能调用this.success2()?有针对此问题的解决方案建议吗?

function myfuntion() {
    this.url = "www.example.com/ajax.php";
    var success1 = function (data) {
        alert("SUCCESS1");
    }
    this.success2 = function (data) {
        alert("SUCCESS2");
    }
    this.send = function () {
        $.ajax({
            type: "POST",
            url: this.url,
            dataType: "html"
        }).done(function (data) {
            success1(data);
            this.success2(data);
        });
    }
}
var test = new myfunction().send();

【问题讨论】:

标签: javascript jquery


【解决方案1】:

正如其他人评论的那样,发送函数中this 的上下文发生了变化,这就是你的success2 函数没有调用的原因。您应该将myFunction 上下文保存在一个变量中,并使用该变量来引用this 上下文。

试试这个:

function myfuntion() {
    var self = this;                // taking the current context in a variable.

    self.url = "www.example.com/ajax.php";
    var success1 = function (data) {
        alert("SUCCESS1");
    }
    self.success2 = function (data) {
        alert("SUCCESS2");
    }
    self.send = function () {
        $.ajax({
            type: "POST",
            url: self.url,
            dataType: "html"
        }).done(function (data) {
            success1(data);
            self.success2(data);
        });
    }
}

【讨论】:

    猜你喜欢
    • 2014-07-31
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 2015-05-11
    相关资源
    最近更新 更多