Js series (3) – closure

What is a closure?

A variable used in a function that is neither a function parameter nor a function local variable

That is, anything inside a function that does not have a var or function declaration can constitute a closure

Closure example

Example 1

var outer = 1; Function f() {console.log(outer)} f() {console.log(outer)} f() {console.log(outer)} f(Copy the code

Example 2

function f() { var num = 1; Return function() {return num}} var num = f() num()Copy the code

Application of closures

What are closures good for? Before es6’s let and const declarations, everyone had trodden this hole

var arr = [];

for (var i = 0; i < 3; i++) {
  arr[i] = function () {
    console.log(i);
  };
}
Copy the code

Arr [0](), ARR [1](), ARR [2](), instant meng! It outputs three 2’s

Why are three 2’s printed?

Let’s take a look at this from my last post on the JS Series (2) : Scope and This

First of all, arR ends up storing three functions, of course

This function is executed when arr[0]() is executed

function () {
  console.log(i);
}
Copy the code

Where I is not declared by var and function, so it forms a closure, where the function has AO = {}, nothing

I is fetched from the external VO of the global scope, and by the time we execute this function, the I in the global VO has changed to 3, so the output of all three functions in arR is 3!

How to solve it?

That’s right, closure

var arr = [];

for (var i = 0; i < 3; i++) {
  arr[i] = (function (i) {
    return function(){
        console.log(i);
    }
  })(i);
}
Copy the code

Again, why do closures work

So first of all, the I of global VO ends up being 3

This function is executed when arr[0]() is executed

(function (i) {
    return function(){
       console.log(i);
    }
})(i)
Copy the code

As you can see, the difference is the self-executing function

Function = function = function = function = function = function = function = function = function It’s the argument I to the self-executing function, which is the value passed in through the loop, so the final output is 0,1,2

Memory leak problem?

There are two basic things to keep in mind here, so we won’t talk about memory leaks in this section

  1. Variables must be declared using var, let, or const

  2. The variable contains the object, a reference to the DOM, and finally assigns the change to NULL