The so-called recursive function call is to call its own function.
1 var NULL ; 2 function A () {3 console.log (123); 4 Timerhandler = SetTimeout (A,n) ; 5 }6A (); 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 following:
var copyfunction = Functionholder;
copyFunction(3);
would output3
2
1
0
As above. If I then changedfunctionHolder
As follows:
Functionholder = function (whatever) { Console.log ("Stop counting!");}
Then functionHolder(3);
would give Stop counting!
, as expected.
copyFunction(3);
Now gives 3
Stop counting!
as it refers functionHolder
to and not the function (which it itself points to). This could being desirable in some circumstances, but is there a-to-write the function so it calls itself rather tha n the variable that holds it?
That's, is it possible-to -change-only-the- functionHolder(counter-1);
going through all these steps still gives 3
When do 1
0
we call copyFunction(3);
? I tried but that this(counter-1);
gives me the error this is not a function
.
----------------------------------------------------------------------------------------------
Using Named Function Expressions:
You can give a function expression a name actually private and are only visible from inside of the Functio N ifself:
VarFactorial= functionMyself(N) { if (n <= 1) { return 1 } return n * Myself (n- 1); }typeof myself === ' undefined '
Here myself
are visible only inside of the function itself.
You can use this private name to call the function recursively.
See the 13. Function Definition
ECMAScript 5 spec:
The Identifier in a functionexpression can is referenced from inside the Functionexpression ' s functionbody to allow the FU Nction to call itself recursively. However, unlike in a functiondeclaration, the Identifier in a functionexpression cannot is referenced from and does not AF Fect the scope enclosing the functionexpression.
Please note this Internet Explorer up to version 8 doesn ' t behave correctly as the name was actually visible in the Enclosi NG variable environment, and it references a duplicate of the actual function (see Patrick DW' s comment below).
JavaScript recursive function calls (recursive Funciton call)