2011-01-27 19 views
6

में कॉलबैक के साथ $ .getJSON() का उपयोग करके मैं एक ऑब्जेक्ट सेट अप करने का प्रयास कर रहा हूं ताकि इसमें $ .getJSON विधि encapsulated हो। यहाँ मेरी सेटअप है:एक जावास्क्रिप्ट ऑब्जेक्ट

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 कॉलबैक फ़ंक्शन जो समझ में आता है अंदर।

क्या इस प्रकार के फ़ंक्शन के लिए कोई कामकाज है या क्या मैं बस इस पूरी तरह गलत तरीके से सोच रहा हूं? मैंने पहले कभी भी PHP ओओ का उपयोग करके कोड किया है ताकि जेएस ओओ मेरे लिए थोड़ा नया हो।

अन्य चीजें मैं कोशिश की है इस प्रकार हैं:

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 

उत्तर

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

धन्यवाद, यह पूरी तरह से काम करता है। –

+0

आपका स्वागत है! – kevingessner

संबंधित मुद्दे