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> |