Questions about Closures in JavaScript

  node.js, question

I what is closure?

Is it that as long as it is a function nested function, whether the local variable of the nested function refers to an external function is a closure, or whether the internal function must return before forming a closure?

1. First example

// #1
 function outer(a,b){
 var c = 999;
 
 function inner(){
 
 console.log(a,b,c);
 
 bracket
 
 inner();  //The internal function was directly called, and no return was returned. Is this a closure?
 
 bracket
 
 /*-dividing line-*/
 
 // #2
 function outer(a,b){
 var c = 999;
 
 //In this case, inner does not refer to the variable of external outer.
 function inner(){
 var d = 2;
 var e = 3;
 Log (d+e);
 
 bracket
 
 inner();  //The internal function was directly called, and no return was returned. Is this a closure?
 
 bracket
 
 
 /*-dividing line-*/
 
 // #3
 function outer(a,b){
 var c = 999;
 
 //In this case, if the str passed in is a variable name, it will refer to the variable in outer.
 function inner(str){
 console.log(eval(str));
 bracket
 
 return inner;
 
 bracket
 var inner = outer(1,2);
 inner("a");  // 1
 inner("b");  // 2
 inner("c");  // 999

If only the function nested function is a closure, then if there is no return inner, there will be no local variables that refer to the outer function (#2). after the outer function is executed, even if the local variables inside the outer exist in memory, no program will access them. then, will GC destroy the local variables inside the outer? However, in the case of #3, although inner does not explicitly call the outer’s local function, this possibility exists, for exampleinner("a")Access outer’s local functiona, then obviously in this case, GC will definitely not destroy outer. .

Alas, it is very confusing anyway. Please give Daniel a feeling of Enlightened? ? ?

2. Second example

function outer(a,b){
 var c = 999;
 
 function inner(){
 
 console.log(a,b,c);
 
 bracket
 
 return inner;  //return the internal function to form a closure, which I am sure of.
 
 bracket

What are the benefits of using closures? How did the memory leak occur?

What we usually call closures (the reason why we say “usually” is because, in a sense, all functions in js are closures-because variables inside functions can be accessed to outside variables. But we only care about the “closure” mentioned below), which has two elements:

  1. Closures reference values in external function vars objects;

  2. Call closures outside of external functions.

The key to understanding closures is:After an external function is called, its variable object should have been destroyed, but the existence of closures still allows us to access the variable object of the external function.

Closure closure!Learn more