好好爱自己!

javascript 递归函数调用(recursive funciton call)

所谓的递归函数调用,就是自己调用自己的函数。

1 var timerHandler = null;
2 function a(){
3     console.log(123);
4     timerHandler = setTimeout(a, 1000)    ;
5 }
6 a();
7 //clearTimeout(timerHandler);

 

-----------------------------------------------------------------------------------------

1
2
3
4
5
6
7
8
/* 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);
3
2
1
0
functionHolder
1
2
3
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 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.

----------------------------------------------------------------------------------------------

Using Named Function Expressions:

You can give a function expression a name that is actually private 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'

Here myself is visible only inside of the function itself.

You can use this private name to call the function recursively.

See 13. Function Definition of the ECMAScript 5 spec:

The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.

Please note that Internet Explorer up to version 8 doesn't behave correctly as the name is actually visible in the enclosing variable environment, and it references a duplicate of the actual function (see patrick dw's comment below).

 
posted @   立志做一个好的程序员  阅读(316)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2017-07-20 开源软件Review Board

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示