2015-09-06 130 views
2

我有一個對象,它簡化了一下的樣子:如何從一個對象中調用一個函數,從javascript中的同一個對象的另一個函數的函數中調用?

function obj(arg){ 
    return{ 
     fct1: function(){ 
      $(".output").append("called fct1 with arg: "+arg+"<br>"); 
     }, 
     fct2: function(){ 
      $(".output").append("called fct2, which has an other function, which calls fct1<br>"); 
      fct2a(); 
      function fct2a(){ 
       $(".output").append("doing something else, then calling fct1<br>"); 
       this.fct1(); //not within scope 
      } 
     } 
     } 
    } 
var myobj = obj("asd"); 
myobj.fct2(); 

我想從fct2a調用fct1,怎麼樣? Fiddle

回答

3

創建一個臨時變量並將該對象設置爲this對象並從中調用。請在下面找到

function obj(arg){ 
    return{ 
     var temp=this; 
     fct1: function(){ 
      $(".output").append("called fct1 with arg: "+arg+"<br>"); 
     }, 
     fct2: function(){ 
      $(".output").append("called fct2, which has an other function, which calls fct1<br>"); 
      fct2a(); 
      function fct2a(){ 
       $(".output").append("doing something else, then calling fct1<br>"); 
       temp.fct1(); 
      } 
     } 
     } 
    } 
var myobj = obj("asd"); 
myobj.fct2(); 
+0

作品,如果我打電話fct2a之前宣佈VAR溫度()。謝謝! –

0

代碼也可以單獨聲明fct1()並調用它在你需要它:

function obj(arg){ 
    function innerFct1(arg) { 
     $(".output").append("called fct1 with arg: "+arg+"<br>"); 
    } 
    return{ 
     fct1: innerFct1, 
     fct2: function(){ 
      $(".output").append("called fct2, which has an other function, which calls fct1<br>"); 
      fct2a(); 
      function fct2a(){ 
       $(".output").append("doing something else, then calling fct1<br>"); 
       innerFct1("arg2"); //not within scope 
      } 
     } 
    } 
} 
var myobj = obj("asd"); 
myobj.fct2(); 
+0

如果innerFct1引入arg,該怎麼辦? –

+0

我編輯了我的答案 – LostMyGlasses

相關問題