Details of the closure of Closure in javascript

  • 2020-11-18 06:06:43
  • OfStack

In javascript, a function can be viewed as a type of data, can be assigned to a variable, and can be nested within another function.


var fun = function(){
  console.log(" Flat inclined ");
}


function fun(){
  var n=10;
  function son(){
    n++;
  }
  son();
  console.log(n);
}
fun(); //11
fun(); //11

Let's change the second paragraph of the above code slightly:


var n=10;
function fun(){
  function son(){
    n++;
  }
  son();
  console.log(n);
}
fun(); //11
fun(); //12

See the difference? If you don't understand the code execution results, see the previous post on javascript scopes and scope chains.

The variable n in the above code is a global variable that can be re-assigned at any time without a call to the fun function. In order for the variable n to not be polluted, or to reduce the contamination of the global variable, we need to put n into the function as a local variable.


function fun(){
  var n=10;
  function son(){
    n++;
    console.log(n);
  }
  son();
}
fun(); //11
fun(); //11

If we can call the son function directly from the global, we can achieve the desired effect. The son function now exists as a local variable, and there are generally two ways to access it globally:

One is to assign values to global variables


var a;
function fun(){
  var n=10;
  a = function son(){
    n++;
    console.log(n);
  }
}
fun(); //son()
a(); //11
a(); //12

The other is to use the return return value


function fun(){
  var n=10;
  return function son(){
    n++;
    console.log(n);
  }
}
var a=fun();
a(); //11
a(); //12

The son() function above is a closure, in the sense that all functions can be considered closures. A closure is a function that accesses a variable in the scope of an outer function.


var a;
function fun(){
  var n=10;
  a = function son(){
    n++;
    console.log(n);
  }
  return a();
}
fun(); //11
a(); //12
a(); //13
fun(); //11
a(); //12
a(); //13

Again, let's modify the code a little bit and see what happens, because the variable n is initialized every time the fun() function is executed.

The advantage of closures is that they reduce global variables, avoid global contamination, and allow local variables to be kept in memory. But this is both an advantage and a disadvantage, because too many closures in a piece of code can cause memory leaks. Since local variables in closures are not collected by the garbage collection mechanism, you need to manually assign them to null (on memory leaks, a separate topic later)


Related articles: