2012-11-10 75 views
1

說我有兩個功能,看起來像這樣:傳遞特定功能變量

function main(Index) 
{ 
    doStuff(); 
} 

function doStuff() 
{ 
    if(Index == 1) 
    { 
     document.write("Hello world!") 
    } 
} 

和一些HTML:

<input type="button" value="Click me" onclick="main(1)" /> 

我意識到這是使用特定功能的變量非常笨的方法等等,但它只是出於好奇。那麼是否可以將變量Indexmain函數傳遞到doStuff函數?

+1

你在找什麼叫做[dynamic scoping](http://en.wikipedia.org/wiki/Scope_(computer_science)#Dynamic_scoping)。有些語言具有此功能,但不支持JavaScript。 – georg

+0

您可以使用簡單的閉包來實現此功能。請參閱下面的答案。 – elucid8

回答

1

那麼有可能將主函數的變量索引傳遞給doStuff函數嗎?

不,沒有明確地將它作爲參數傳遞給doStuff。無論是doStuff需要接受一個參數,也可能利用arguments集合:

function main(index) 
{ 
    doStuff(index); 
} 

function doStuff() 
{ 
    var index = arguments[0]; 

    if(index == 1) 
    { 
     document.write("Hello world!") 
    } 
} 
+0

不是我同意用他的方法(我會剔除中間人),但爲什麼不建議他使用內部函數來完成呢?請參閱下面的答案。 – elucid8

+0

@ elucid8他沒有提供足夠的背景。我專門回答了他的問題。他可能無法在他的場景中「剪掉中間人」...... – xandercoded

1

這是唯一的出路:

function doStuff(Index) 
{ 
    if(Index == 1) 
    { 
     document.write("Hello world!") 
    } 
} 

或使其成爲一個全局變量

1

你爲什麼要轉變的是調用DoStuff函數?

是不是Main對事件和「做東西」作出反應?

如果是那樣的話,你應該保持該功能在Main,像這樣:

function Main(index){ 
    switch (index){ 
     case 1: 
      DoStuff(); 
      break; 
     case 2: 
      DoStuff2(); 
      break; 
     default: 
      DoStuff(); //Because, why not? 
    { 
} 

function DoStuff(){ 
    document.write("Hello, world!"); 
} 

function DoStuff2() {//something else happens here} 

您沒有使用Main作爲對象,因此沒有必要的持久性(據我知道)。只要切斷不必要的電話,你的生活就會變得更簡單。然而,如果你想要實現這種功能,你可以創建一個簡單的閉包。它應該是這樣的:

<input type="button" onclick="Main(1);" value="Do Something" /> 

<script type="text/javascript"> 
function Main(index) { 

    //This function only exists within the scope of Main 
    function DoStuff() { 

     //But now it has the added benefit of knowing about index 
     switch (index) { 
     case 1: 
      alert("Hello, world!"); 
      break; 
     case 2: 
      alert("Not, really. I'm mad."); 
      break; 
     default: 
      alert("Hello, world!"); 
     } 
    } 

    //Now Main is going to call it's internal function and... 
    DoStuff(); 
} 
</script> 

既然你的Main身體這意味着DoStuff存在的Main詞法範圍之內,將有機會獲得所有成員中聲明DoStuff。關閉功能非常強大,但很容易濫用它們。如果你真的需要這種功能,我會建議走這條路,否則,KISS(Keep It Simple Sir)。