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

时间:2011-01-27 15:56:41

标签: javascript ajax jquery

我正在尝试设置一个对象,以便它具有封装的$ .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',这是有道理的。

这种类型的功能是否有解决方法,或者我只是想错误的方法?我之前只使用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

1 个答案:

答案 0 :(得分:8)

你的第一次尝试已接近,但正如你所说,你无法在回调中访问this,因为它引用了其他内容。相反,将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;
}