I can create a recursive function in a variable as follows:
var functionHolder = function (counter) { output(counter); if (counter > 0) { functionHolder(counter-1); } }
At the same time functionHolder(3); prints 3 2 1 0 . Say I did the following:
var copyFunction = functionHolder;
copyFunction(3); outputs 3 2 1 0 as above. If I then changed the functionHolder as follows:
functionHolder = function(whatever) { output("Stop counting!");
Then functionHolder(3); will give Stop counting! , as expected.
copyFunction(3); now gives 3 Stop counting! , since it refers to a functionHolder , and not to the function (to which it points). This may be desirable in some cases, but is there a way to write a function so that it calls itself, and not the variable that holds it?
That is, is it possible to change only the line functionHolder(counter-1); , so going through all these steps still gives 3 2 1 0 when we call copyFunction(3); ? I tried this(counter-1); but this gives me the error this is not a function .
javascript function recursion
Samthere Aug 15 '11 at 12:51 on 2011-08-15 12:51
source share