js closure

Closures are almost a must for interviews. It is one of the essence of js.

 

definition:

1. A function defined inside a function

2. Functions used to read internal variables of other functions

3. A bridge that connects the inside of the function with the outside

ps: Anonymous functions belong to closures

 

usefulness:

1. You can read the variables inside the function

2. Let the value of the variable always remain in memory and not be recycled by the garbage collection mechanism

 

shortcoming:

Memory consumption is high, which may lead to memory leaks

 

usage:

Return a function inside the A function to save the internal variables of the A function for external access at the same time

function A(){
  var num=1;
  return function(){
    console.log(num++)
 }  
}

var a= new A();
a   //1;
a   //2;

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326261706&siteId=291194637