js递归调用
1 function fact(num) { 2 if (num <= 1) { 3 return 1; 4 } else { 5 return num * fact(num - 1); 6 } 7 }
以下代码可导致出错:
1 var anotherFact = fact; 2 fact = null; 3 alert(antherFact(4)); //出错
由于fact已经不是函数了,所以出错。
用arguments.callee可解决问题,这是一个指向正在执行的函数的指针,arguments.callee返回正在被执行的对现象。
新的函数为:
1 function fact(num) { 2 if (num <= 1) { 3 return 1; 4 } else { 5 return num * arguments.callee(num - 1); //此处更改了。 6 } 7 } 8 var anotherFact = fact; 9 fact = null; 10 alert(antherFact(4)); //结果为24.
程序员的基础教程:菜鸟程序员
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步