0

I have the following code in JavaScript and jQuery with an integrated ajax request. Question: Why is it possible to call the inner function success1() but it is not possible to call this.success2() ? Any solution proposals for this problem?

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();
4

1 回答 1

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);
        });
    }
}
于 2013-04-06T11:15:40.483 回答