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. 

 程序员的基础教程:菜鸟程序员

posted on 2014-04-10 21:45  itprobie-菜鸟程序员  阅读(40346)  评论(0编辑  收藏  举报