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
  • 相关阅读:
    由于信号量apache启动问题
    argument list too long
    Read-only file system处理
    fuser
    strace命令基本用法
    c++ 对vector和deque进行逆序排序问题
    C++ 遍历vector容器的三种方式
    C++ 中关于重复读取ifstream中的内容所需要注意的问题
    C++中的文件写入和读取(文本文件方式,二进制方式)
    Unity DoTween插件 在代码中改变Ease(运动方式)
  • 原文地址:https://www.cnblogs.com/PrajnaParamita/p/5779674.html
Copyright © 2011-2022 走看看