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
  • 相关阅读:
    python函数对象
    生成器表达式,列表推导式
    python转换excel成py文件
    Python处理excel表
    Go基础:接口相关
    JAVA03-输入和输出
    python6-while循环
    python5-字典
    自动化8-xpath
    网络学习day1-计算机网络基础
  • 原文地址:https://www.cnblogs.com/PrajnaParamita/p/5779674.html
Copyright © 2011-2022 走看看