2012-03-23 7 views
2

Ich möchte eine Ajax-Anfrage, die immer noch Zugriff auf das aktuelle Objekt behält. Weiß jemand, ob das möglich ist?Javascript OOP - jQuery Aufruf "dieses" in Ajax-Anfrage

Beispiel von dem, was ich tun möchte:

function mobile_as(as_object, inputID) { 
    this.object = 'something'; 
    if (as_object) this.object = as_object; 
    this.inputID = inputID; 

    // Get results for later usage. 
    this.get_results = function(value) { 
      this.request = $.getJSON("URL", { as: this.object }, function (data) { 
       // Scope of "this" is lost since this function is triggered later on. 
       if (data['status'] == "OK") { 
        alert(this.inputID); 
       } 
      }); 
     } 
    } 
} 
+1

FYI Javascript OOP nicht. – jrummell

+0

@jrummell Das ist subjektiv, nicht wahr? http://stackoverflow.com/questions/107464/is-javascript-object-oriented – teynon

+0

Ich denke nicht, aber Sie sind frei zu widersprechen. – jrummell

Antwort

8

Verschlüsse zur Rettung:

function mobile_as(as_object, inputID) { 
    var self = this; // <--------- 
    this.object = 'something'; 
    if (as_object) this.object = as_object; 
    this.inputID = inputID; 

    // Get results for later usage. 
    this.get_results = function(value) { 
      this.request = $.getJSON("URL", { as: this.object }, function (data) { 
       // Scope of "this" is lost since this function is triggered later on. 
       self.... //self is the old this 
       if (data['status'] == "OK") { 
        alert(self.inputID); 
       } 
      }); 
     } 
    } 
} 
+0

Wissen Sie, ob das Selbst eine Referenz oder eine Kopie wird? Ich habe das früher gemacht, aber ich fürchte, wenn ich das tue und das tatsächliche Objekt während der Anfrage modifiziert wird, erstelle ich im Wesentlichen eine Race Condition. Oder schafft dies eine Referenz? – teynon

+0

@Tom Objekte werden immer durch Referenz in JavaScript zugewiesen. – jnrbsn

+0

'self' ist eine Referenz. – apsillers