在Javascript对象中使用$ .getJSON()和回调

我正在尝试设置一个对象,以便它有一个封装的$ .getJSON方法。 这是我的设置:

function Property(price, deposit){ this.price = price; this.deposit = deposit; this.getMortgageData = function(){ $.getJSON('http://example.com/index?p='+this.price+'&d='+this.deposit+'&c=?', function(data){ this.mortgageData = data; }); } return true; } 

现在问题似乎是我无法在getJSON回调函数中访问’this’,这是有道理的。

这种类型的function是否有解决方法,或者我只是在想这个错误的方法? 我之前只使用PHP OO进行过编码,所以JS OO对我来说有点新鲜。

我尝试过的其他事情是:

  function Property(price, deposit){ this.price = price; this.deposit = deposit; this.getMortgageData = function(){ this.mortgageData = $.getJSON('http://example.com/index?p='+this.price+'&d='+this.deposit+'&c=?', function(data){ return data; }); } return true; } 

但是,

 var prop = new Property(); prop.getMortgageData(); // wait for the response, then alert(prop.mortgageData.xyz); // == undefined 

你的第一次尝试很接近,但正如你所说,你无法在回调中访问this ,因为它引用了其他东西。 而是将其分配给外部作用域中的另一个名称,并访问该名称。 回调是一个闭包,可以访问外部作用域中的变量:

 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; }