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

 

posted @ 2016-08-17 13:38  chenccc  阅读(451)  评论(0编辑  收藏  举报