zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    eclipse改变默认的编码格式(UTF-8)
    Guava学习:Joiner和Splitter工具(二)
    Guava中的Joiner和Splitter工具演示
    GitHub查找开源项目技巧分享
    java1.8特性之多重排序简单示例
    jedis工具类:java操作redis数据库
    SQL优化建议(mysql)
    Moodle插件之Filters(过滤器)
    Moodle插件开发系列——XMLDB编辑器
    Moodle插件开发——Blocks(版块)
  • 原文地址:https://www.cnblogs.com/PolarisSky/p/5274957.html
Copyright © 2011-2022 走看看