I\'m trying to set up an object so that it has an encapsulated $.getJSON method. Here\'s my setup:
function Property(price, deposit){
this.price = price;
Your first attempt is close, but as you said, you can't access this
inside the callback because it refers to something else. Instead, assign this
to another name in the outer scope, and access that. The callback is a closure and will have access to that variable in the outer scope:
function Property(price, deposit){
this.price = price;
this.deposit = deposit;
var property = this; // this variable will be accessible in the callback, but still refers to the right object.
this.getMortgageData = function(){
$.getJSON('http://example.com/index?p='+this.price+'&d='+this.deposit+'&c=?', function(data){
property.mortgageData = data;
});
}
return true;
}