2012-03-23 50 views
2

我想創建一個仍然保留訪問當前對象的ajax請求。有誰知道這是否可能?的想什麼,我做Javascript OOP - jQuery在ajax請求中調用「this」

例子:

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

僅供參考JavaScript並不是OOP。 – jrummell 2012-03-23 19:58:30

+0

@ jrummell這是主觀的不是嗎? http://stackoverflow.com/questions/107464/is-javascript-object-oriented – teynon 2012-03-23 20:07:06

+0

我認爲不是,但你可以自由地不同意。 – jrummell 2012-03-23 20:09:22

回答

8

瓶蓋救援:

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

你知道自己是成爲參考還是副本?我早些時候做過,但是我擔心如果我這樣做並且實際的對象在請求期間被修改,我會基本上創建競爭條件。還是使用這個創建一個參考? – teynon 2012-03-23 19:54:59

+0

@Tom對象始終通過JavaScript中的引用進行分配。 – jnrbsn 2012-03-23 19:57:23

+0

'self'是一個參考。 – apsillers 2012-03-23 19:57:49