Error-prone points in recursion

Source: Internet
Author: User

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

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.