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

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM