This is the fourth day of my participation in Gwen Challenge

What is a closure? This is a difficult problem to understand in javaScript.

The ECMAScript definition for a closure is: a closure is a lexical representation of a function that includes variables that are not evaluated. That is, a function can use variables defined outside of the function. Doesn’t it make this definition more difficult to understand? So let’s analyze it.

  1. A closure is a function
  2. Closures can call defined variables outside of their own functions
  3. The closure exists in a scope that defines the variable

So what is a variable outside the function definition? Let’s first look at how the scope of a function variable works.

Variable scope

Variables can be divided into global variables and local variables. Global variables are global in scope and can be used anywhere in JS. When the var keyword is used in a function to declare a variable, the variable is a local variable. Its scope is only in the function that declares the variable, and the variable is not accessible outside the function.

var func = function(){
    var a = 'dddd';
    console.log(a);         // dddd
}
func();
console.log(a);             // Uncaught ReferenceError: a is not defined

Copy the code

Let’s look at the lifetime of a variable that has more to do with closures.

Variable life cycle

Global variables, the life cycle is permanent. A local variable that is collected and destroyed by the garbage collection mechanism when the function call that defined it ends. The next call to the function redefines a new variable.

var func = function(){
    var a = 'ddd';
    console.log(a);
}
func();
Copy the code

A is a local variable that is destroyed when func is called.

var func = function(){
    var a = 'ddd';
    var func1 = function(){
        a += ' a';
        console.log(a);
    }
    return func1;
}
var func2 = func();
func2();                    // ddd a
func2();                    // ddd a a
func2();                    // ddd a a a
Copy the code

As you can see, after the first call to func2, the variable a in func becomes’ DDD a’ instead of being destroyed. Because func1 now forms a closure, the life cycle of A continues.

Now the closure is a little clearer.

  • A closure is a function, such as func1 above
  • Closures use variables defined by other functions so that they are not destroyed. For example, func1 calls the variable A above
  • The closure exists in the scope in which the variable is defined, and the variable A exists in the scope of func, so func1 must also exist in the scope.

Now we can say that closures are the ones that satisfy all three of these conditions.