Using $.getJSON() with callback within a Javascript object

后端 未结 1 831
夕颜
夕颜 2021-01-05 12:34

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;
          


        
相关标签:
1条回答
  • 2021-01-05 13:20

    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;
    }
    
    0 讨论(0)
提交回复
热议问题