javascript再帰関数呼び出し(recursive funciton call)

5622 ワード

再帰関数とは、自分で自分の関数を呼び出すことです.
1 var timerHandler = null;
2 function a(){
3     console.log(123);
4     timerHandler = setTimeout(a, 1000)    ;
5 }
6 a();
7 //clearTimeout(timerHandler);
 
-------------------------------------------------------
/* Count down to 0 recursively.
 */
var functionHolder = function (counter) {
    console.log(counter);
    if (counter > 0) {
        functionHolder(counter-1);
    }
}
 
With this、  functionHolder(3); would output  3  2  1  0.Let's say I did the followwing:
var copyFunction = functionHolder;
copyFunction(3); would output 3 2 1 0 as above. If I then changed functionHolder as follows:
functionHolder = function(whatever) {
    console.log("Stop counting!");
}
  
The n  functionHolder(3); would give  Stop counting!、as expected.copyFunction(3); now gives  3  Stop counting! as it refers to  functionHolder,not the function.This could be desirable in some circestancs,but is there a way to write the function so that cars it cars it cars the variable the Holds?
That is、is it possible to change only オンライン  functionHolder(counter-1); so that going through all these steps still gives  3  2  1  0 when we call  copyFunction(3);I tried  this(counter-1); but that gives me the error  this is not a function.
------------------------------------------------
Using Named Function Expressions:
You can give a function expression a name that is actually prvate and is only visible from inside of the function ifself:
var factorial = function myself (n) { if (n <= 1) { return 1; } return n * myself(n-1); } typeof myself === 'undefined'
ヘレ  myself is visible only inside of the function itself.
You can use this prvate name to cal the function recursively.
See  13. Function Definition of the ECMAScript 5 spec:
The Identifiier in FuntititionExpressition can be referenced from ininininde the FunctititinExpressision's FuntitititititinFuntititititititititinnFlow the FFunctctctctctctctctctctctctctctctctctctcttttttttttttcacacacacacacacacacacacacacarerererelllllllllllphphphphrerererererererererererererererererererererererererererererererererererererely.Hofefefefefefefefefefefeion.
Please note that Internet Explorer up to version 8 doesn't behave corectlyas the name is actually visible in the enclosing variable environment,and it references a duplicate of the actual function(see) patrick dw'sコメントbelow)