2011-04-11 141 views
0

我有一個酒吧類:如何獲取Bar實例?

function Bar() { 
    this.myMethod = function() { 
     $.ajax({ 
      ..., 
      success: function(msg){ 
       // I can't get Bar instance with 'this' 
      } 
     }); 
    } 
} 

如果Ajax是成功的,我想這樣做與酒吧實例的東西。我該怎麼辦?爲ajax調用之外的實例創建var?

回答

4
function Bar() { 
    var self = this; 
    this.myMethod = function() { 
     $.ajax({ 
      ..., 
      success: function(msg){ 
       //Use self here. 
      } 
     }); 
    } 
} 
+0

是的,我的想法是,我們必須添加一個變量。我正在尋找更簡單的一個。順便說一句,你使用'self'關鍵字作爲變量名? – 2011-04-11 08:07:26

+0

我看不到它比這更簡單。你可以使用任何你喜歡的變量名稱,我只是想保持它的相關性。 – Alex 2011-04-11 08:11:14

1

您可以使用一個變量,像亞歷克斯建議,或創建一個包含封閉的包裝功能:如果你想保持它的簡單

[...] 
this.myMethod = function() { 
    $.ajax({ 
      ..., 
      success: (function (context) { 
       return function(msg){ 
       //Use context here. 
       } 
      }(this)) 
     }); 

    } 
[...] 

不過,我會去亞歷克斯的建議,因爲它更明顯發生了什麼。

+0

好的我正在使用他的建議..但我真的知道這種技術,謝謝! – 2011-04-11 08:35:49