The classic factorial function

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

This factorial function uses a recursive algorithm, which is fine if the function has a name and the name doesn’t change. But the problem is that the execution of this function is tightly coupled with the name factorial. When assigning a factorial function to another name, it is easy to fail to complete the recursive call. Inside the function, there is one special object called Arguments. Arguments’ primary use is to hold function arguments, but it has a callee property that is useful for recursive calls. The Callee property is a pointer to the current function that has arguments objects. So our factorial function can be rewritten as:

function factorial() {if(num <= 1){
        return 1;
    }else{
        returnnum * arguments.callee(num - 1); }}Copy the code

The function body of the rewritten factorial() function no longer refers to the function name factorial. This ensures that the recursive call completes normally, regardless of the name used to refer to the function. Implementation:

var trueFactorial = factorial;
alert (trueFactorial(5)); / / 120Copy the code