使用命名函数表达式编写递归函数 factorial

Posted Pooc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用命名函数表达式编写递归函数 factorial相关的知识,希望对你有一定的参考价值。

递归函数通常的形式是一个函数通过名称调用自己

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

如果把这个函数赋值给其他变量,就会出问题

let anotherFactorial = factorial; 
factorial = null; 
console.log(anotherFactorial(4)); // 报错

可以使用命名函数表达式(named function expression)达到目的

const factorial = (function f(num) {
    if (num <= 1 ) {
        return 1
    } else {
        return num * f(num - 1)
    }
})

let anotherFactorial = factorial; 
factorial = null; 
console.log(anotherFactorial(4)); // 24

以上是关于使用命名函数表达式编写递归函数 factorial的主要内容,如果未能解决你的问题,请参考以下文章