JavaScript Closures vs. Anonymous Functions
In JavaScript, a closure occurs when an inner function has access to the outer scope's variables, even after the outer function has completed execution. Many functions in JavaScript are considered closures, but only a specific subset is of particular interest theoretically.
Case 1: Friend's Code
<code class="js">(function f() { var i2 = i; setTimeout(function g() { console.log(i2); }, 1000); })();</code>
Case 2: Your Code
<code class="js">setTimeout((function f(i2) { return function g() { console.log(i2); }; })(i), 1000);</code>
Conclusion
Therefore, in both the provided solutions, the inner function g is a closure, but not the outer ones. This demonstrates that although they achieve the same result, they do so through different mechanisms.
The above is the detailed content of Is an inner function always a closure in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!