2014-05-25 142 views
1

如何從JavaScript中的對象內的函數調用另一個函數。如何在對象函數中調用另一個函數

例如,我試圖做到這一點:

var mydiv1 = document.querySelector('.div1'); 
var mydiv2 = document.querySelector('.div2'); 

var myVariable1; 
var myVariable2; 

var myObject = (function() { 
    return { 
     function1 : function (myVariable1) { 
      myVariable2 = "this was called from a function and inserted by function2"; 
      mydiv1.innerHTML = myVariable1; 
      function2(myVariable2); 
     }, 

     function2 : function (myVariable2) { 
      mydiv2.innerHTML = myVariable2; 
     } 
    }; 

}()); 

mydiv1.addEventListener('click', function() { 
    myVariable1 = "this was called from a function and inserted by function1"; 
    myVariable2 = "this was called from a function and inserted by function2"; 
    myObject.function1(myVariable1); 
}); 

這裏是一個小提琴http://jsfiddle.net/kvtxd/6/

「功能1」運行爲例外,但我得到一個錯誤,函數2是不確定的。這樣做的正確方法是什麼?

我使用對象的原因是,我可以根據需要單獨調用每個內部函數。我只是調用function2但不是function1。

看,如果我使用:

function WholeFunction() { 
    function function1() { 
    // 
    } 
    function function2() { 
    // 
    } 
} 

然後功能1和功能2超出範圍,我只能叫了整個事情。

回答

2

使用「本」關鍵字時,在函數內部:

function1 : function (myVariable1) { 
      myVariable2 = "this was called from a function and inserted by function2"; 
      mydiv1.innerHTML = myVariable1; 
      this.function2(myVariable2); // use "this" here!!!! 
     }, 

這裏有一個Fiddle

+1

它總是小事! – user3143218

+0

「this」是指對象,變量還是函數? – user3143218

+0

@ user3143218:'this'指對象。 – Guffa

相關問題