To understand closures, you need to know JavaScript variable scope

  1. The global variable

  2. A local variable

    const a = 1 function func(){ console.log(a); } func() // 1 functions can read global variables internally

    function f1(){ const a=1; } console.log(a) // Uncaught ReferenceError: a is not defined outside the function cannot read local variables inside the function

In addition, ES6’s const and let have their own concept of block-level scope.

Sometimes, we just need to get local variables in the function, what do we do? Closures are designed to solve this problem.

function f1(){ const n=1; function f2(){ console.log(n); } return f2; } const result=f1(); result(); / / 1Copy the code

So the concept of a closure, as I personally understand it, is that a closure is a function defined inside a function.

Please correct me if there is something wrong

The f2 function is a closure defined inside f1.

In addition to allowing external functions to read variables inside functions, another user of closures is to keep the values of those variables in memory at all times.

function f1() { let n = 1; function f2() { n = n + 1; console.log(n); } return f2; } const result = f1(); result(); // 2 result(); // 3 result(); // 4 result = null // Release reference to closureCopy the code

The variable n in function f1 is kept in memory and is not automatically cleared after f1 is called. Because f1 is the parent of F2, and F2 is assigned to the global variable result, f2 is always in memory, and f2 depends on F1, so F1 is always in memory and is not collected by the garbage collection mechanism after the call ends.

Closures are commonly used to create private variables and methods

Function Person() {// private const age = 11; function run() { console.log(2); } this.getage = function () {return age; }; } const age = new Person(); console.log(age.getAge()); / / 11Copy the code