2012-07-17 60 views
0

嗨,我放棄了這個。任何人都可以幫助我或有另一種方式來調用函數?如何在函數外調用此函數?

+0

爲什麼不把外面的第二個功能? – Mithir 2012-07-17 06:36:30

+0

我發現這個鏈接很有用http://hungred.com/how-to/tutorial-function-function-javascript/ – Kasma 2012-07-17 06:37:36

+0

你真的想做什麼? – Tamil 2012-07-17 06:56:05

回答

0
var stringWord; 
function firstFunction() 
{ 
    stringWord = "Hello World"; 
    secondFunction(); 
} 

function secondFunction() 
    { 
    alert(stringWord); 
    } 

function thirdFunction() 
{ 
    run = setTimeout('secondFunction()' , 5000); 
} 
+0

這是行不通的。結果是未定義的。 – 2012-07-17 06:45:30

+0

什麼結果? – Aesthete 2012-07-17 06:48:57

1
function firstFunction() 
{ 
    stringWord = "Hello World"; 
    return function secondFunction()//How to call this function in thirdfunction() ?? 
    { 
    alert(stringWord); 
    }; 
} 

secondFunction = firstFunction(); 

function thirdFunction() 
{ 
    run = setTimeout('secondFunction()' , 5000); 
} 

的jsfiddle:http://jsfiddle.net/DRfzc/

+0

嘿,這有幫助。非常感謝你。 – 2012-07-17 07:04:56

+0

考慮將其標記爲問題的正確答案,然後;) – Samuel 2012-07-17 07:08:37

2

試試這個:

function firstFunction() 
     { 
      stringWord = "Hello World"; 
      this.secondFunction = function()//How to call this function in thirdfunction() ?? 
      { 
      alert(stringWord); 
      } 
     } 
     var instand = new firstFunction(); 
     function thirdFunction(){ 
      run = setTimeout('instand.secondFunction()', 5000); 
     } 

希望這有助於。

+0

這很好,它運行良好。謝謝你的幫助。 – 2012-07-17 07:05:27

1

沒有修改firstFunction()沒有辦法從firstFunction()外部撥打secondFunction()。如果這是可以接受的請繼續閱讀...

方法1:修改firstFunction()一個參考返回secondFunction()

function firstFunction() { 
    stringWord = "Hello World"; 
    return function secondFunction() { 
    alert(stringWord); 
    } 
} 
// And then call `firstFunction()` in order to use the function it returns: 
function thirdFunction() { 
    run = setTimeout(firstFunction(), 5000); 
} 
// OR 
var secondFunc = firstFunction(); 
function thirdFunction() { 
    run = setTimeout(secondFunc, 5000); 
} 

方法2:有firstFunction()把一個參考secondFunction()在其範圍以外的變量訪問:

var secondFunc; 
function firstFunction() { 
    stringWord = "Hello World"; 
    function secondFunction() { 
    alert(stringWord); 
    } 
    window.secondFunc = secondFunction; // to make a global reference, AND/OR 
    secondFunc = secondFunc; // to update a variable declared in same scope 
          // as firstFunction() 
} 
firstFunction(); 
function thirdFunction() { 
    run = setTimeout(secondFunc, 5000); 
} 

需要注意的是,無論什麼方法,你必須真正呼叫firstFunction()嘗試使用INNE前r功能。

+0

這是非常有幫助!非常感謝你。當我嘗試這個時,我感覺很好。 – 2012-07-17 07:19:46