I can’t access the attribute of an instantiated class. The attribute is set using an AJAX call.
I am trying to define the class “CurrentUser”, and then set the attribute “userId” using AJAX.
Here I define the class CurrentUser, and give it the attribute userID:
function CurrentUser() {
// Do an ajax call to the server and get session data.
$.get("../../build/ajaxes/account/get_user_object_data.php", function(data) {
this.userId = data.userId;
console.log(data.userId); // This will correctly output "1".
}, "JSON");
}
Here I instantiate a CurrentUser named billybob. Notice how I can’t output billybob’s attribute:
// Instantiate the user.
var billybob = new CurrentUser();
console.log(billybob.userId); // This will incorrectly ouput "undefined".
I’ve checked the common errors with AJAX:
-
The AJAX call returns the data correctly as a JSON object. I can read the correct object in Firebug / Network console. The AJAX call also has a status of “200” and “OK”.
-
I can log the AJAX call’s data correctly, as seen in the first part of my code where I log data.userId.
Maybe this clears it out:
In your original code:
You are creating an anonymous function on the fly, that will be later called by jQuery’s internals with
thisset to an ajax object. So
thiswill be the ajax object inside the anonymous function, notbillybob. So whenyou do
this.userId = ...thismeans the ajax object which doesn’t have a userid property.jQuery will have no idea where you got your callback function from, so it cannot set the
thisautomagicallyfor you.
What you must do is to save the
billybob(or anyCurrentUserinstance) reference and use it in the callback like so:Also note that:
By the time you call
console.log(I.E. instantly after creatingbillybob), the ajax request hasn’t been completed yet so it isundefined.