I can create a recursive function in a variable like so:
/* Count down to 0 recursively.
*/
var functionHolder = function (counter) {
output(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 output 3
2
1
0
as above. If I then changed functionHolder
as follows:
functionHolder = function(whatever) {
output("Stop counting!");
Then functionHolder(3);
would give Stop counting!
, as expected.
copyFunction(3);
now gives 3
Stop counting!
as it refers to functionHolder
, not the function (which it itself points to). This could be desirable in some circumstances, but is there a way to write the function so that it calls itself rather than the variable that holds it?
That is, is it possible to change only the line 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
.