Recursive functions, which have been briefly introduced in the previous blog. A recursive function is a function that calls itself within a function by its name. As follows:
1 function FAC (num) { 2 if (Num<1 3 return 1; 4 } 5 else { 6 return NUM*FAC (num-1 7 } 8 }
The above code declares a FAC function on the first line and calls the FAC function itself in 6 rows. This is a recursive function that asks for factorial.
1 var anthorfacc=FAC; 2 fac=null; 3 ANTHORFACC (4); // Throw Exception
The above code, in the first line, declares a variable ANTHORFACC and points to FAC. The 2nd row of FAC sets NULL, so ANTHORFACC is also null. An exception is thrown when the 3rd line is called, because the FAC function is called two times when the factorial is being evaluated, but after FAC is set to NULL, there is actually only one remaining reference to FAC. In this case, calling FAC inside the function will cause an error. In this case, using Arguments.callee can solve the above problem.
Arguments.callee is a pointer to an execution function that can be used to implement recursive invocation of a function.
1 functionFAC (num) {2 if(num<1){3 return1;4 }5 Else{6 returnNum*arguments.callee (num-1);7 }8 }9 varAnthorfacc=FAC;TenFac=NULL; One varJIE=ANTHORFACC (4); AConsole.log (Jie);// -
The above code replaces the function itself with Arguments.callee, and does not error even if FAC is set to NULL. However, the strict mode in ES5 is not allowed to use the callee method, access to this property will be an error. You can use a named function expression to express the same result.
1 varFac= (functionf (num) {2 if(num<1){3 return1;4 }5 Else{6 returnNUM*FAC (num-1);7 }8 });9 varAnthorfacc=FAC;TenFac=NULL; One varJIE=ANTHORFACC (4); AConsole.log (Jie);// -
The above code creates a named function expression named F, and assigns its value to FAC. Even if the function FAC is assigned to another variable, the function f is still valid, so the recursive function is still valid. This usage can be used in both strict and non-strict modes.
On the function expressions of JavaScript (recursion)