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);
                }
            });
        }
    }
}
3
  • @jrummell That's subjective isn't it? stackoverflow.com/questions/107464/… Commented Mar 23, 2012 at 20:07
  • I think not, but you are free to disagree. Commented Mar 23, 2012 at 20:09
  • People who think OOP means "Class" generally stink at OOP in any programming language. Commented Mar 23, 2012 at 21:31

1 Answer 1

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);
                }
            });
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@Tom Objects are always assigned by reference in JavaScript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.