2011-01-27 13 views
6

Estoy tratando de configurar un objeto para que tenga un método $ .getJSON encapsulado. Aquí está mi configuración:

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

Ahora el problema parece ser que no tengo acceso a 'esto' dentro de la función de devolución de llamada getJSON que tiene sentido.

¿Hay alguna solución para este tipo de función o simplemente estoy pensando en esta manera totalmente incorrecta? Solo he codificado alguna vez usando PHP OO antes, así que JS OO es algo nuevo para mí.

Otras cosas que he probado son:

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

Pero aún así,

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

Respuesta

8

Su primer intento está cerca, pero como se ha dicho, no se puede acceder this dentro de la devolución de llamada, porque se refiere a otra cosa. En su lugar, asigne this a otro nombre en el alcance externo y acceda a eso. La devolución de llamada es un cierre y tendrá acceso a esa variable en el ámbito exterior:

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

Gracias, funcionó perfectamente. –

+0

¡De nada! – kevingessner

Cuestiones relacionadas