This is the 10th day of my participation in the August Challenge. Check out the August Challenge for details

preface

Closures are a concept that front-end engineers need to understand well, but there are some articles on the web that can be confusing for beginners. There are numerous articles about closures, and the quality of the articles varies.

In this article, for beginners, I will take you through my understanding of closures and walk you through them step by step with examples.

What is a closure?

Let’s start with what the authority says:

JavaScript Advanced Programming (version 4)

Closures are functions that refer to variables in the scope of another function, usually implemented in nested functions.

MDN defines closures as:

A combination of a function bound to (or surrounded by) references to its surrounding state (lexical environment) is a closure.

What is the definition of closure?

Here, we will first throw out the closure summarized by Professor Fang Yinghang, and then we will explain the “function” and “variables that can be accessed inside the function”

The sum of “function” and “variables accessible within the function” is a closure.

Understand closures by example

Let’s start with an example:

function init() {
    var name = "Mozilla";
    function sayName() {
        console.log(name); // "Mozilla"
    }
    sayName();
}
init();
Copy the code

Run the code above and the output is “Mozilla”.

Let’s see, why is the output “Mozilla”? So let’s do this step by step.

In the example above, there is the init function scope, the sayName function scope, and the global scope. Their relationship is shown as follows:

When the sayName function is called, console.log(name) is executed; SayName = sayName; sayName = sayName; sayName = sayName; sayName = sayName; sayName = sayName; sayName = sayName;

What do I do to find name? Understandably, at this point, the JS engine pokes its head out, goes to the upper scope (init), finds the name, and is ready to use.

In this search process, a scope chain is formed by successive layers of scope, and the scope chain relationship is shown as follows:

To return to this statement, the sum of the function and the variables accessible from within the function is a closure.

The sayName function and the variable name in the init function, which is a closure, are Closures.

From the figure above, we can see that closures live in a gray area between the scope of a function and a variable.

The above example is a good refutation of the closure interpretation of “function nested function, and then return a function”.

In JS, closures exist to allow indirect access to variables inside functions.

reference

  • Learn Javascript closures
  • What are closures in QUESTION of the Day JS?
  • JavaScript deep closure

If there are any mistakes in this article, please correct them in the comments section. If this article helped you or you liked it, please like it and follow it.