2014-02-26 57 views
1

早上好,我正在從JavaScript的函數式編程方法轉向面向對象的方法學,並且有一個問題。在函數式編程我可以調用一個函數另一個函數內。例如:JavaScript OOP參考方法

function a(){ 
    // do something and when done call function b 
    b(); 
} 

function b(){ 
    // does more stuff 
} 

現在,我切換到OOP的做法我將如何調用對象的方法從同一個對象的另一種方法。例如:

var myClass = function(){ 
    this.getData = function(){ 
     //do a jquery load and on success call the next method 
     $('#a').load('file.asp',function(response,status,xhr){ 
      switch(status){ 
       case "success": 
        //THIS IS WHERE THE QUESTION LIES 
        this.otherfuntcion(); 
       break; 
      } 
     } 
    } 

    this.otherfunction = new function(){ 
     // does more stuff 
    } 
} 

p = new myClass(); 
p.getData(); 

我可以說this.b()成功調用方法b還是必須做別的事情?先謝謝你。

+0

拼寫錯誤。 'this.otherfunction()' –

+0

就像一個資源可以幫助你一樣.. http://stackoverflow.com/a/13074081/1257652 –

回答

5

這將是更非常緩慢方法和很多實例。改用原型:

var myClass = function(){ 

} 
myClass.prototype = { 
    getData: function(){ 
     //do a jquery load and on success call the next method 
     $('#a').load('file.asp',function(response,status,xhr){ 
      switch(status){ 
       case "success": 
        //THIS IS WHERE THE QUESTION LIES 
        this.otherfunction(); 
       break; 
      } 
     }.bind(this)) 
    }, 
    otherfunction: new function(){ 
     // does more stuff 
    } 
}; 


p = new myClass(); 
p.getData(); 
+0

不是'this'裏面的完全回調是指jqXHR對象嗎? –

+0

不,綁定'改變了回調的範圍... – inf3rno

+0

對不起,沒有看到它 –

1

您的匿名回調函數中的this上下文與您的類的方法內部的上下文不同。因此,你需要一個參考存到自己的上下文閉包內:

var that = this; 
$('#a').load('file.asp',function(response,status,xhr){ 
    switch(status){ 
     case "success": 
      //THIS IS WHERE THE QUESTION LIES 
      that.otherfuntcion(); 
     break; 
    } 
}); 

的替代將是一個特定的上下文綁定到你的匿名函數:

$('#a').load('file.asp',function(response,status,xhr){ 
    switch(status){ 
     case "success": 
      //THIS IS WHERE THE QUESTION LIES 
      this.otherfuntcion(); 
     break; 
    } 
}.bind(this)); 
+0

我們通常在這種情況下調用一個'bind'來改變作用域,使用'''','自我'等等,不推薦很長時間。 – inf3rno

0

您應該將外部函數上下文複製到新變量中,以直接引用外部上下文。 this在內部功能是這個內部功能的上下文。

var self = this; 
$('#a').load('file.asp',function(response,status,xhr){ 
    switch(status){ 
     case "success": 
      //THIS IS WHERE THE QUESTION LIES 
      self.otherfuntcion(); 
     break; 
    } 
}