English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This article analyzes the JavaScript recursive operation. Shared with everyone for reference, as follows:
Problem
A simple recursion to calculate the factorial of n:
function factorial(n){ if (n<=1) { return 1; } return factorial(n-1)*n; } }
If it is used as shown below, an error will occur:
var fcopy = factorial; factorial = null; alert(fcopy(3));
Because the function entity pointed to by fcopy has called factorial, and factorial has been released.
A solution to this problem
Using arguments.callee
When the execution flow enters the function, a function's execution environment (scope chain, etc.) is created, including the special object arguments. The arguments object has a property pointing to the function itself: arguments.callee.
function factorial(n){ if (n<=1) { return 1; } return arguments.callee(n-1)*n; } }
However, callee is not available in strict mode.
Using Function Expression
var factorial = (function f(n){ if (n<=1) { return 1; } return f(n-1)*n; } )
This is not using any new technology, but just an application of the original concept. When defining factorial, a function is directly created, and the reference of this function is assigned to factorial.
Readers who are interested in more content related to JavaScript can check the special topics on this site: 'Summary of JavaScript Traversal Algorithms and Techniques', 'Summary of JavaScript Array Operation Techniques', 'Summary of JavaScript Mathematical Operation Usage', 'Summary of JavaScript Data Structures and Algorithm Techniques', 'Summary of JavaScript Switching Effects and Techniques', 'Summary of JavaScript Search Algorithm Techniques', 'Summary of JavaScript Animation Effects and Techniques', and 'Summary of JavaScript Error and Debugging Techniques'.
I hope the content described in this article will be helpful to everyone in JavaScript program design.
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)