Home > Web Front-end > JS Tutorial > body text

When Does an Anonymous Function Become a Closure in JavaScript?

Mary-Kate Olsen
Release: 2024-10-31 08:05:02
Original
971 people have browsed it

When Does an Anonymous Function Become a Closure in JavaScript?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!