Recursive function problem in JavaScript

Anyone who has learned other programming languages ​​should know the problem of recursion. Recursive functions are formed after a function calls itself by name.

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

This is a relatively classic factorial algorithm. This way of writing implements what we call recursion. This code seems to have no problem, there are such descriptions in c or other programming languages. But sometimes things go wrong in JavaScript.

For example:

<span style="white-space:pre">	</span>var myfac=fac;
	fac = null;
	console.log(myfac(4));//Error
 
  

Why would it go wrong?
According to the truth, fac refers the original function to myfac, and then sets fac to be empty. The reference to the original function is still in myfac, and it should be able to access it. This fails, when calling myfac, because fac() must be run. At this point fac is no longer a function, so it will cause the error, in this case using arguments.callee (pointing to the running function) can solve the problem.

function fac (num) {
		if(num<=1){
			return 1;
		}else{
			return num*arguments.callee(num-1);
		}
	}

By using arguments.callee instead of the function name, you can ensure that no matter how you call the function, there will be no problems. So, when writing recursive functions. Using arguments.calllee() is always safer than using function names.

But in strict mode, it is not possible to access arguments.callee through script, accessing this property will cause an error, but you can use named function expressions to achieve the same effect.

var fac = (function f (num) {
		if(num<=1){
			return 1;

		}else{
			return num*f(num-1)
		}
	});
Complete. .. ..



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324452584&siteId=291194637