Closure (JS you don't know)

What exactly is a closure

Find out the difference between lexical scope and closure search

function foo() {
  var a = 2;
  function bar() {
    console.log(a);
  }
  return bar;
}
var baz = foo();
baz(); // 2 -- friend, this is the effect of closure.

bar() can obviously be executed normally. But in this case, it is executed outside its own defined lexical scope.
This function is called outside the lexical scope at the time of definition.
Closures allow functions to continue to access the lexical scope at the time of definition.
Say more: the bar function that should have been used as garbage collection, because the internal function is called outside, which makes the closure function. Finally, the garbage collection can't be recycled and can continue to be used.
No matter how the internal function is passed outside the lexical scope, it will hold a reference to the original definition scope. No matter where the function is executed, it will use closures. The process of keeping lexical scope intact is closure.

above return This is a method. You can also use external functions and built-in functions to react to produce effects during function operation.
function foo() {
  var a = 2;
  function baz() {
    console.log(a); // 2
  }
  bar(baz);
}
function bar(fn) {
  fn(); // Mom, look, this is the closure!
}

Or adopt indirect methods:
var fn;
function foo() {
  var a = 2;
  function baz() {
    console.log(a);
  }
  fn = baz; // Assign baz to global variable
}
function bar() {
  fn(); // Mom, look, this is the closure!
}
foo();
bar(); // 2

Whenever and wherever, if you treat functions (accessing their respective lexical scopes) as the first
Level value types and pass them around, and you'll see the application of closures in these functions. On timers, event listeners
Ajax requests, cross window communication, Web Workers, or any other asynchronous (or synchronous) task, as long as
Using a callback function is actually using a closure!

Loops and closures

The callback of the delay function is executed at the end of the loop.

for (var i = 1; i <= 5; i++) {
  setTimeout(function timer() {
    console.log(i);
  }, i * 1000);
}

What defects in the code cause its behavior to be inconsistent with that implied by semantics?

The drawback is that we try to assume that each iteration in the loop "captures" a copy of i at run time. However, according to the working principle of scope, the actual situation is that although the five functions in the loop are defined separately in each iteration, they are enclosed in a shared global scope, so there is actually only one i.

We need more closure scopes, especially one for each iteration of the loop.
As described in Chapter 3, IIFE creates a scope by declaring and immediately executing a function.
Then in order to achieve the effect:

This will not work:
for (var i = 1; i <= 5; i++) {
  (function () {
    setTimeout(function timer() {
      console.log(i);
    }, i * 1000);
  })();
}

We obviously have more lexical scope now. Indeed, each delay function encloses the scope created by IIFE in each iteration.
If scopes are empty, it is not enough to just close them. Take a closer look, our IIFE is just an empty scope with nothing. It needs some substance to be used by us.

for (var i = 1; i <= 5; i++) {
  (function () {
    var j = i;
    setTimeout(function timer() {
      console.log(j);
    }, j * 1000);
  })();
}
// All right! It's working!.
// Some improvements can be made to this Code:
for (var i = 1; i <= 5; i++) {
  (function (j) {
    setTimeout(function timer() {
      console.log(j);
    }, j * 1000);
  })(i);
}
Of course, these IIFE It's just a function, so we can i Pass it in. If you like, you can set the variable name to j,Of course, it can also be called i. 
Anyway, this code is now working.
Use within iteration IIFE A new scope will be generated for each iteration, so that the callback of the delay function can enclose the new scope within each iteration,
Each iteration will contain a variable with the correct value for us to access.

Closure + block scope“

After five cycles, there are five block scopes. However, because the same scope was used before the cycle, 6 are output. Now there are 5. Each time the callback function is mounted, J is assigned. Therefore, 12345 of the five scopes are printed (callback function)

for (var i = 1; i <= 5; i++) {
  let j = i; // Yes, the block scope of closure!
  setTimeout(function timer() {
    console.log(j);
  }, j * 1000);
}

Each scope is declared directly, and the i of the previous scope is used to assign values to the next scope

for (let i = 1; i <= 5; i++) {
  setTimeout(function timer() {
    console.log(i);
  }, i * 1000);
}

modular

Closures and module exposure, as the name suggests, if you understand what is written above.
What is exposed is the function or attribute inside the function (module). After the function is executed once, the internal scope and closure will not be available until the instance is created.
Similar to public API

Import can import one or more APIs in a module into the current scope and bind them to a variable (hello in our example). Module will import and bind the API of the whole module to a variable (foo and bar in our example).
Export will export an identifier (variable, function) of the current module as a public API.
These operations can be used as many times as needed in the module definition.
The contents of the module file will be treated as if they were contained in the scope closure, just like the function closure module described earlier.

Keywords: Javascript JQuery Ajax

Added by r_a_s_robin on Wed, 24 Nov 2021 08:46:32 +0200