One-sentence closure

  • Closures allow functions to access and manipulate variables outside the function -JS Ninja cheats
  • Closures are functions that have access to variables in the scope of another function – the Little Red book
  • Closures are functions that have access to free variables, in this case MDN, a variable in the scope of the external function

scope

To understand closures, you must first understand Javascript’s special variable scope. There are two main scopes of variables: global scope and function scope. Second: block-level scope let’s look at the following code

  // Global scope
  var a = 1;
  var f = 5;

  function fu() {// Function scope
    var a = 2;
    var b = 3;
    console.log(a, f); / / 2, 5
  }

  fu();
  console.log(a); //  1
  // console.log(b); // b is not defined

  if (true) {// block-level scope
    var c = 5;
    let d = 6;
  }
  console.log(c); //  5
  // console.log(d); // d is not defined
Copy the code

Here’s what makes Javascript language special:

  • Global variables can be read directly from inside functions
  • (b is not defined)
  • Variables created by let/const in the block-level scope cannot be read externally.

Effect of chain

When the executable code accesses a variable internally, it looks in the local scope first, returns if it finds the target variable, and continues in the parent scope otherwise… XXX is not defined if global scope is not found.

Closure formation

Let’s look at subcolumn 1:

    var b =13
    function foo(){
        var b =14
        return function fo(){
            console.log(b) 
        }
    }
    foo()() / / 14
Copy the code

We might wonder, isn’t the code above equivalent to the following? Column 2:

    var b =13
    function fo(){
            console.log(b) 
    }
    fo() / / 13
Copy the code

If we look at this column, it’s the same thing as column 2. Column 3:

    var b =13
    function foo(){
        return function fo(){
            console.log(b) 
        }
    }
    foo()(); / / 13
Copy the code

A closure is a function that has access to a variable in the scope of another function.

  • Access a variable in another function scope
  • It’s a function

Column 1 is a closure

    var b =13
    function foo(){
        var b =14
        return function fo(){ // a function
            // this accesses a variable in the scope of another function.
            console.log(b) 
        }
    }
    foo()() / / 14
Copy the code

The role of closures

Implement modularity to protect private variables from external intrusion. A common approach uses self-executing functions to implement closure modularity

// Self-executing functions are modularized
/ / module 1
(function () {
    var a = 1;
    console.log(a); / / 1}) ();/ / module 2
(function () {
    var a = 2;
    console.log(a); / / 2}) ();Copy the code

The a variable of module 1 and module 2 is non-intrusive.

Closure problems

    function father(){
        var b =14
        return function child(){
            console.log(b) 
        }
    }
    foo()() / / 14
Copy the code

The father function is isolated from the outside world. All references to variables are done inside the father function. After father is run, the internal variables should be destroyed and memory reclaimed. However, closures result in the existence of a child function in the global scope that refers to the b variable in father. This means that the child function defined in father always has a reference number of 1, and the garbage mechanism cannot destroy it. The engine can’t tell when you’re going to call closure functions again, so it just keeps letting the data eat up memory, leading to a memory leak.

A memory leak is a condition in which a block of memory is not returned to the operating system or memory pool for some reason when it is no longer being used by an application. A memory leak can cause an application to stall or crash.

Classic Interview questions

Q: Analyze the results of its actual operation

    for (var i = 0; i < 3; i++) { 
        setTimeout(() = > console.log(i),0); 
    }
    / / 3 3 3
Copy the code

Q: Modify it to output 0 1 2 1.es6

    for (let i = 0; i < 3; i++) { 
        setTimeout(() = > console.log(i),0)}/ / 0 1 2
Copy the code

2. SetTimeout The third parameter

    for (var i = 0; i < 3; i++) { 
        setTimeout((t) = > console.log(t),0,i)
    }
    / / 0 1 2
Copy the code

3. The closure

    for (var i = 0; i < 3; i++) { 
       (function () {console.log(i)})()
    }
    / / 0 1 2
Copy the code

Relevant reference

Juejin. Cn/post / 684490…