JavaScript Closures vs. Anonymous Functions
Anonymous functions, a common feature in JavaScript, often arise in discussions of closures. However, not all anonymous functions qualify as true closures.
Defining Closures
A closure in JavaScript is a special type of anonymous function that retains access to the lexical scope in which it was created, even after the outer scope has ended. This feature allows closures to "capture" the values of variables from the outer scope, preventing them from being garbage collected.
Case Study: Closing Over a Variable
In the given code examples, both solutions use anonymous functions to delay the printing of the counter variable i.
Friend's Attempt
The code in the first example seems to capture the i variable within the closure. However, it does not meet the definition of a closure because the inner anonymous function g does not inherit the lexical scope of the outer function f. Thus, i is not actually "closed over."
<code class="javascript">for(var i = 0; i < 10; i++) { (function(){ var i2 = i; setTimeout(function(){ console.log(i2); }, 1000) })(); }</code>
Editor's Attempt
The second code example truly creates a closure. The anonymous function returned by the outer function f captures the i2 variable and preserves its value within the closure's lexical scope. This closure is then called within the setTimeout callback, ensuring that the i variable's original value is accessed.
<code class="javascript">for(var i = 0; i < 10; i++) { setTimeout((function(i2){ return function() { console.log(i2); } })(i), 1000); }</code>
Conclusion
In the provided code, the editor's solution demonstrates the correct use of a closure to capture the value of the i variable. While both solutions effectively solve the issue of delayed printing, only the editor's solution qualifies as a closure in the technical sense.
The above is the detailed content of When Does an Anonymous Function Become a Closure in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!