I saw the seventh chapter of the JavaScript Advanced programming program, so I sorted it out.
Not very likely to use the editor code here to make a mess ...
Some error-prone points in recursion and errors that occur
1. Call itself by the function name, when the function is assigned to another variable, and then the function becomes null or other non-function value
For example
function factorial (num) {if (num<=1) {return 1; } else{return num*factorial (num-1); }}
This is called by the function name factorial.
If you use
var anotherfactorial = Factorial;factorial = Null;alert (anotherfactorial (4));//Error! {{{(>_<)}}}
Because factorial is not a function anymore, it will execute the return num*factorial(num-1) when using Anotherfactorial; Will cause errors
So you can use Arguments.callee to solve
Let's review the Arguments.callee.
Arguments is a class array object that contains all the parameters passed into the function. The main function is to save the function parameters.
It has a property called Callee, which is a pointer to the function that owns the arguments object.
So even if the recursive function has a different name, it can be called (Θ).
2. In strict mode, however, Arguments.callee cannot be accessed through a script, which results in an error.
So you can use a named function expression to do it.
var factorial = (function f (num) {if (num<=1) {return 1; } else{return Num*f (num-1); }});
F () is an intrinsic function so even if the outer order f= NULL; It still works correctly.
This article is from the "Write Code Guo Degang" blog, be sure to keep this source http://atuzi.blog.51cto.com/7743360/1753492
Error-prone points in recursion