Javascript学习笔记:3种递归函数中调用自身的写法

①一般的通过名字调用自身

1 function sum(num){
2   if(num<=1){
3     return 1;
4   }else{
5     return num+sum(num-1);
6   }
7 }
8 
9 console.log(sum(5));//15

 这种通过函数名字调用自身的方式存在一个问题:函数的名字是一个指向函数对象的指针,如果我们把函数的名字与函数对象本身的指向关系断开,这种方式运行时将出现错误。

 1 function sum(num){
 2   if(num<=1){
 3     return 1;
 4   }else{
 5     return num+sum(num-1);
 6   }
 7 }
 8 console.log(sum(5));//15
 9 
10 var sumAnother=sum;
11 console.log(sumAnother(5));//15
12 
13 sum=null;
14 console.log(sumAnother(5));//Uncaught TypeError: sum is not a function(…)

②通过arguments.callee调用函数自身

 1 function sum(num){
 2   if(num<=1){
 3     return 1;
 4   }else{
 5     return num+arguments.callee(num-1);
 6   }
 7 }
 8 console.log(sum(5));//15
 9 
10 var sumAnother=sum;
11 console.log(sumAnother(5));//15
12 
13 sum=null;
14 console.log(sumAnother(5));//15

这种方式很好的解决了函数名指向变更时导致递归调用时找不到自身的问题。但是这种方式也不是很完美,因为在严格模式下是禁止使用arguments.callee的。

 1 function sum(num){
 2   'use strict'
 3   
 4   if(num<=1){
 5     return 1;
 6   }else{
 7     return num+arguments.callee(num-1);
 8   }
 9 }
10 console.log(sum(5));//Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them(…)

③通过函数命名表达式来实现arguments.callee的效果。

 1 var sum=(function f(num){
 2   'use strict'
 3   
 4   if(num<=1){
 5     return 1;
 6   }else{
 7     return num+f(num-1);
 8   }
 9 });
10 
11 console.log(sum(5));//15
12 
13 var sumAnother=sum;
14 console.log(sumAnother(5));//15
15 
16 sum=null;
17 console.log(sumAnother(5));//15

这种方式在严格模式先和非严格模式下都可以正常运行。

 

posted @ 2016-03-14 11:02  北极星空  阅读(7043)  评论(0编辑  收藏  举报