The problem of recursive function in JavaScript

Source: Internet
Author: User

All other programming languages should know about recursion, and recursive functions are formed after a function calls itself by name.

function FAC (num) {if (num<=1) {return 1;} Else{return NUM*FAC (num-1);}}

This is a more classical factorial algorithm, which implements what we call recursion. This code does not seem to be a problem, it is described in C or in other programming languages, but sometimes it goes wrong in JavaScript. Just like:

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

Why did it go wrong?
In accordance with the reason that FAC references the original function to the MYFAC, and then set the FAC to NULL, the reference to the original function is still in the MYFAC, it should be accessible to ah! This is problematic, when calling Myfac, because FAC () must be executed, and FAC is no longer a function, it will cause an error, in which case the use of Arguments.callee (pointing to the Executing function) resolves 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 the function is called, it is much safer to use Arguments.calllee () when writing a recursive function than to use the function name.

However, in strict mode, it is not possible to access the Arguments.callee through a script, access to this property can cause errors, but you can use a named function expression to achieve the same effect.

var fac= (function f (num) {if (num<=1) {return 1;} Else{return num*f (Num-1)});
Finish spicy ...



The problem of recursive function in JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.