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();
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Anne Droid
  • 3,151
  • 4
  • 16
  • 15
  • 2
    Because inside the callback, `this` refers to another object. – Felix Kling Apr 06 '13 at 11:13
  • You may want to take a look at the accepted answer for http://stackoverflow.com/questions/3127429/javascript-this-keyword for an excellent explanation of JavaScript's 'this' – frostmatthew Apr 06 '13 at 13:44

1 Answers1

1

As other commented, the context of this inside the send function is changed, so that's why your success2 function is not calling. You should save myFunction context in a variable and use that variable to refer this context.

Try 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);
        });
    }
}
Gaurav
  • 8,367
  • 14
  • 55
  • 90