JS中的递归函数

// 经典的写法
    function test(n) {
        if (n <= 1) {
            return 1;
        } else {
            return  n * test(n-1);
        }
    }
    test(4) // 24

上面的写法是没有问题的 ,但是如果遇到函数表达式的写法,可能会报错,比如:

 function test(n) {
        if (n <= 1) {
            return 1;
        } else {
            return  n * test(n-1);
        }
    }
    var t = test;
    test = null;
    t(); // test is not a function

这就是函数调用函数的弊端,那怎么解决呢,用 arguments.callee 来解决,但是arguments.callee 这个方法被弃用了,所以我们用的时候,要注意使用场景和使用方法:

1.使用递归的时候,函数是声明式的写法(声明式函数和表达式函数自行百度,或者看我另外一篇博客),避免出现 test is not a function 这种错误

2.参考文档:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments/callee

原文地址:https://www.cnblogs.com/0955xf/p/12634307.html