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
  • 相关阅读:
    nginx 状态码整理
    nginx 添加perl
    Nginx 内置全局变量
    数组模板实现(新手遇到的格式问题)
    malloc的使用注意事项
    使用memset的注意事项!!!
    2019/3/31acm周三(三人)/CodeForces
    2019/3/31acm周三(三人)/LightOJ
    2019/3/31acm周三(三人)/hdu1042/高精度计算(未懂!)
    2019/3/24周赛坑题(读题)HDU 1412
  • 原文地址:https://www.cnblogs.com/PrajnaParamita/p/5779674.html
Copyright © 2011-2022 走看看