3

I would like to make an ajax request that still retains access to the current object. Does anyone know if this is possible?

Example of what I'd like to do:

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);
                }
            });
        }
    }
}
teynon
  • 7,540
  • 10
  • 63
  • 106

1 Answers1

10

Closures to the rescue:

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);
                }
            });
        }
    }
}
asawyer
  • 17,642
  • 8
  • 59
  • 87
  • Do you know if self becomes a reference or a copy? I did that earlier, but I fear if I do that and the actual object gets modified during the request, I'll essentially create a race condition. Or does using this create a reference? – teynon Mar 23 '12 at 19:54
  • @Tom Objects are always assigned by reference in JavaScript. – jnrbsn Mar 23 '12 at 19:57