Home >Web Front-end >JS Tutorial >Is Your Friend\'s JavaScript Code Actually Using Closures?

Is Your Friend\'s JavaScript Code Actually Using Closures?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 06:11:02529browse

Is Your Friend's JavaScript Code Actually Using Closures?

JavaScript Closures vs. Anonymous Functions

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:

  • The function f is not a closure because all free variables (i, setTimeout, and console) are bound to the global scope, and none of them are closed over.
  • The function g, however, is a closure because it closes over the variable i2, which is bound to the scope of f. When g is referenced from within setTimeout, it retains access to i2.

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:

  • The function f is not a closure because it has no free variables.
  • The function g, however, is a closure because it closes over the variable i2, which is bound to the scope of f. When g is referenced from within setTimeout, it retains access to i2.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn