我可以像这样在变量中创建递归函数:
/* Count down to 0 recursively.
*/
var functionHolder = function (counter) {
output(counter);
if (counter > 0) {
functionHolder(counter-1);
}
}
有了这个,functionHolder(3);将输出3 2 1 0. 假设我做了以下事情:
var copyFunction = functionHolder;
copyFunction(3);将3 2 1 0如上输出。如果我然后更改functionHolder如下:
functionHolder = function(whatever) {
output("Stop counting!");
然后functionHolder(3);会给Stop counting!, 正如预期的那样。
copyFunction(3);现在给出3 Stop counting!它所指的functionHolder,而不是函数(它本身指向的)。在某些情况下这可能是可取的,但是有没有办法编写函数以便它调用自身而不是保存它的变量?
也就是说,是否可以仅更改线路functionHolder(counter-1);,以便3 2 1 0在我们调用时仍然执行所有这些步骤copyFunction(3);?我试过this(counter-1);了,但这给了我错误this is not a function。