惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

TaoSecurity Blog
TaoSecurity Blog
Jina AI
Jina AI
雷峰网
雷峰网
月光博客
月光博客
The GitHub Blog
The GitHub Blog
WordPress大学
WordPress大学
B
Blog RSS Feed
美团技术团队
C
CXSECURITY Database RSS Feed - CXSecurity.com
小众软件
小众软件
Security Latest
Security Latest
Microsoft Azure Blog
Microsoft Azure Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
Cybersecurity and Infrastructure Security Agency CISA
Last Week in AI
Last Week in AI
A
Arctic Wolf
Latest news
Latest news
Attack and Defense Labs
Attack and Defense Labs
I
Intezer
F
Fortinet All Blogs
罗磊的独立博客
MongoDB | Blog
MongoDB | Blog
Webroot Blog
Webroot Blog
S
Secure Thoughts
Help Net Security
Help Net Security
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
V
Visual Studio Blog
P
Proofpoint News Feed
博客园 - 【当耐特】
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
Stack Overflow Blog
Stack Overflow Blog
Know Your Adversary
Know Your Adversary
云风的 BLOG
云风的 BLOG
Hacker News: Ask HN
Hacker News: Ask HN
L
LINUX DO - 最新话题
H
Help Net Security
爱范儿
爱范儿
酷 壳 – CoolShell
酷 壳 – CoolShell
S
SegmentFault 最新的问题
Forbes - Security
Forbes - Security
T
Tailwind CSS Blog
量子位
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Tenable Blog
Cloudbric
Cloudbric
N
News and Events Feed by Topic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog

博客园 - chenping2008

连接远程数据库,得到数据插入本地表中 php复制目录 PHP删除目录 php统计目录大小 js秒数转换天时分秒 JS切换图片 js 游览器log的记录 2个iframe中checkbox联动 JS Clone函数 JS随机数的产生方法 JS相等运算符(==)和等同运算符(===) silverlight树形结构区服选择 Mongodb的一些基本概念 Mongodb在Ubuntu下的安装 redis windows下使用及redis命令 相册功能 Node.js 系列翻译---console Node.js 系列翻译---概要 补充Silverlight中图片显示
JS普通递归的改进
chenping2008 · 2012-09-09 · via 博客园 - chenping2008

递归函数是在一个函数通过名字调用自身的情况下构成的,如下所示:

function factorial(num)
{
    if(num<=1)
    {
        return 1;
    }
    else
    {
        return num * factorial(num-1);
    }

}

这是一个经典的阶乘函数。表面看来没有什么问题,但下面的代码却可能导致它出错。

var anotherFactorial = factorial;

anotherFactorial(4); //输出 24

 factorial = null;

 anotherFactorial (4); //TypeError: Property 'factorial' of object [object Window] is not a function   chrome 下测试

原因在于,我们定义的函数名,其实是指向函数的一个指针,此时定义了anotherFactorial 也指向了那个函数,所以调用anotherFactorial (4)可以成功的输出24

此时 factorial = null; 那么执行定义函数的引用就剩下了anotherFactorial,那么在调用anotherFactorial(4)就会显示以上的错误的信息。

此时可以使用arguments.callee来替代函数定义中的 factorial,

函数的定义就变成了:

 function factorial(num)

{
    if(num<=1)
    {
        return 1;
    }
    else
    {
        return num * arguments.callee(num-1);
    }
}

 那么在使用上面的4行测试代码,最后一行测试代码也可以成功的输出24. 

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

上述的内容摘自<<JavaScript高级程序设计>>第2版 144页 7.1节