Reputation: 1686
I have the following code that creates an object in JavaScript. It uses prototype to define functions and constructors.
function objectClass(){
this.variables = new Array();
}
objectClass.prototype =
{
contructor: objectClass,
setInfo: function(){
$.ajax({
url: "info.json",
success: function(){
//for each json element returned...
this.variables.push(json[i]);
}
});
}
getInfo: function(){
return this.variables;
},
}
This is a similar example of what I am trying to do. I need to be able to return the array of variables when I call obj.getInfo(). It always throws an error. I believe it is because the "this" is referring to the scope of the ajax success function.
Any ideas on how to get it to reference the objects variable?
Upvotes: 0
Views: 299
Reputation: 154818
That's correct, the this
value is not automatically passed and thus not set to the instance. To force this, you can use the context
property that $.ajax
accepts:
$.ajax({
context: this, // `this` is the instance here
This sets the this
value inside the success callback to the one you specified.
Upvotes: 4