• JavaScript学习笔记(八)--- 函数表达式


    1.递归

    实现一:

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

    但给factorial重赋值时,再调用就会出错。

    var anotherFactorial = factorial;
    factorial = null;
    alert(anotherFactorial(4)); //TypeError: factorial is not a function

    实现二:

    使用arguments.callee解决上面问题。

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

    修改factorial,再调用

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

    实现三:

    在严格模式下,不能通过脚本访问arguments.callee。解决办法,使用命名函数表达式。

    var factorial = (function f(num){
        if(num<=1){
            return 1;
        }else{
            return num*f(num-1);
        }    
    });
    
    alert(factorial(4)); //24

    以上代码创建了一个名为f()的命名函数表达式,然后将它赋值给变量factorial。

    把函数赋值给另一个变量,函数的名字f仍然有效。这种方式在严格模式和非严格模式下都行得通。

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

    2.闭包

  • 相关阅读:
    BZOJ 3282: Tree( LCT )
    BZOJ 3713: [PA2014]Iloczyn( 枚举 )
    HDU3974
    CodeForces220B
    POJ2349
    HDU3038
    POJ1611
    IELTS
    POJ1125
    POJ2109
  • 原文地址:https://www.cnblogs.com/yanyangbyou/p/3961276.html
Copyright © 2020-2023  润新知