Home >Web Front-end >JS Tutorial >Is Your Friend\'s JavaScript Code Actually Using Closures?
Question:
In a discussion about closures in JavaScript, one friend claimed that their implementation lacked closures, while the other argued the opposite. Can you determine which solution uses closures by applying the concept of closures?
Solution:
Closure Definition: A closure in JavaScript refers to a subset of functions with free variables (variables defined in a parent scope) that are referenced from a different scope. When a closure is referenced outside its parent scope, it closes over the upvalue (the free variable) from that scope.
Case 1: Your Friend's Program
<code class="js">for (var i = 0; i < 10; i++) { (function f() { var i2 = i; setTimeout(function g() { console.log(i2); }, 1000); })(); }</code>
Analysis:
Case 2: Your Program
<code class="js">for (var i = 0; i < 10; i++) { setTimeout((function f(i2) { return function g() { console.log(i2); }; })(i), 1000); }</code>
Analysis:
Conclusion:
Both you and your friend are using closures in your implementations. The difference is that in your friend's program, the closure is created within the inner function g, while in your program, the closure is created within the outer function f.
The above is the detailed content of Is Your Friend\'s JavaScript Code Actually Using Closures?. For more information, please follow other related articles on the PHP Chinese website!