1. 程式人生 > >3種遞迴函式中呼叫自身的寫法

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
複製程式碼

這種方式在嚴格模式先和非嚴格模式下都可以正常執行。