zoukankan      html  css  js  c++  java
  • JS函数表达式 -- 递归

    递归函数: 函数通过名字调用自身

    function factorial(num){
        if(num <= 1){
            return 1;
        }else{
            return num * factorial(num - 1);
        }
    }

    上述代码时一个经典的递归阶乘函数。当执行下面的代码时会出错:

    var anotherFactorial = factorial;
    factorial = null;
    alert(anotherFactorial(4));

    以上代码先把factorial()函数保存在变量anotherFactorial()中,然后将factorial变量设置为null, 结果指向原始函数的引用只剩下一个。但在接下来调用anotherFactorial()时,由于必须执行factorial(),而factorial已经不再是函数,所以就会导致错误。在这种情况下,使用arguments.callee可以解决这个问题。

    arguments.callee是一个指向正在执行的函数指针。

    function factorial(num){
        if(num <= 1){
            return 1;
        }else{
            return num * arguments.callee(num - 1);
        }
    }
    var anotherFactorial = factorial;
    factorial = null;
    alert(anotherFactorial(4));    //24

    在严格模式下,不能通过脚本访问arguments.callee,访问这个属性会导致错误:

    function factorial(num){
        "use strict";
        if(num <= 1){
            return 1;
        }else{
            return num * arguments.callee(num - 1);
        }
    }
    Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects 
    for calls to them

    可以使用命名函数表达式来达成相同的结果:

    var factorial = (function f(num){
        if(num <= 1){
            return 1;
        }else{
            return num * f(num-1);
        }
    });
    var anotherFactorial = factorial;
    factorial = null;
    alert(anotherFactorial(4));    //24
  • 相关阅读:
    关于springMVC+Mybatis jar包详解
    关于struts2的过滤器和mybatis的插件的分析
    C# Zip压缩、解压
    JS 字符串转字节截取
    JS 时间差计算 XX秒前、XX小时前、XX天前
    IIS配置web.config 将带www域名转为不带www域名
    JavaScript获取当前url路径
    SQL 查询今天、昨天、7天内、30天的数据
    SQL求解两个时间差
    SqlServer获取当前日期
  • 原文地址:https://www.cnblogs.com/PrajnaParamita/p/5779674.html
Copyright © 2011-2022 走看看