Js arguments. callee implements recursion of anonymous Functions

Source: Internet
Author: User

Let me introduce you to the specific operation methods and examples of implementing anonymous functions using js arguments. callee. For more information, see.

Recursive Algorithms are familiar to everyone. For example, a recursive function for finding the sum of 0 to n is as follows:

The Code is as follows: Copy code

Var fn = function (n ){
If (n> 0) return n + fn (n-1 );
Return 0;
}
Alert (fn (10 ))

Of course, this is a very simple function. If we only need to call this function once in a very complicated program, we must try to define fewer function names to simplify the function, it is natural to think of using anonymous functions for direct execution. But how does an anonymous function implement recursion? Arguments. callee comes in handy. It refers to the reference of the currently executed function.

The recursion implemented by using anonymous functions is as follows:

The Code is as follows: Copy code

Var s = (function (n ){
If (n> 0) return n + arguments. callee (n-1 );
Return 0;
}) (10 );
Alert (s)


Arguments. callee () is a pointer pointing to a function with this arguments! Its application can be reflected in the classic factorial function:

The Code is as follows: Copy code

<Script type = "text/javascript">
// Factorial function
Function factorial (num) {// factorial is just a pointer to the front-end variable object of the execution environment
If (num <1 ){
Return 1
} Else {
Return num * arguments. callee (num-1); // The callee attribute is a pointer pointing to a function that owns this arguments
}
}
Var anotherFunc = factorial;
Factorial = function () {// variable factorial, reference type value, pointing to another variable object in memory, not the original variable object
Return "abc ";
}
// Function factorial () {// different from the above function expression, the modified variable object directly affects anotherFunc.
// Return "abc ";
//}
Alert (anotherFunc (5 ));
</Script>

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.