So, I created an object which makes an AJAX call to populate its properties during the initialization phase. However, I am running into a very weird behaviour: I can print and see the property values fine within the $.ajax() scope, but any public method that returns the value of properties have a return value of “undefined”.
Here’s what the JS code looks like:
function MyFunction() {
this.myProperty;
this.init();
}
Myfunction.prototype.getPropertyValue = function () {
alert(this.myProperty); // returns 'undefined'
}
Myfunction.prototype.init = function () {
$.ajax({
type: 'get',
url: "getProperty.php",
dataType: "json",
success: function(response) {
this.myProperty = response[0].Property;
alert(this.myProperty) // returns 'Property Name'
}
});
}
My thinking is that within the $.ajax() scope, ‘this’ is actually referring to something else. So, my question is how do I make sure that ‘this.myProperty’ is set and doesn’t lose its value once we get outside of the AJAX scope?
Any help is much appreciated.
Part of the reason why you’re getting “undefined” because of the way you establish the value:
When you declare properties (or variables) without specifying a value, they default to “undefined”. Instead:
On to the ajax call. You are right that the scope of the callback is not the same as the object.
this, in the ajax success function, refers to the jQuery-wrapped XHR object. When you callthis.myProperty = response[0].Property, you are actually creating a new property on the ajax object and setting its value. To correct this, you can either use thecontextoption of the jQuery ajax object, OR bind the callback function using the javascriptbindmethod:… or:
Try it here: http://jsfiddle.net/SnLmu/
Documentation
bind()on MDN – https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bindjQuery.ajax()– http://api.jquery.com/jQuery.ajax/