Closure is a very important threshold for mastering Javascript from the human door to the depth. It is a difficult and characteristic of the Javascript language. Many advanced applications rely on closures for implementation.
Closure-ubiquitous
In front-end programming, using closures is very common. We often use closures intentionally or unintentionally, directly or indirectly. Closures make data transmission more flexible (such as processing click events)
! Function () {var localData = "localData here"; document. addEventListener ('click', // external local variables are used for processing click events, for example, localData function () {console. log (localData );});}();
Another example is as follows: (is it very kind ~~)
!function() { var localData = "localData here"; var url = "http://www.baidu.com/"; $.ajax({ url : url, success : function() { // do sth... console.log(localData); } }); }();
Let's take a look at an example ~~ This is what we usually call the closure.
function outer() { var localVal = 30; return function(){ return localVal; } } var func = outer(); func(); // 30
In this example, outer () is called to return the anonymous function (), which can access the local variable localVal of outer (). After outer () is called, when you call func () Again, you can still access the local variable localVal of outer ().
Closure concept
A closure is different from a common function. It allows a function to access non-local variables when the function is called out of the lexical scope immediately. -- Wikipedia
A closure is a function that can read internal variables of other functions. -- Ruan Yifeng
In Javascript, only the subfunctions in a function can read local variables. Therefore, you can simply understand the closure as a function defined in a function ".
Therefore, in essence, closure is a bridge connecting the internal and external functions of a function.
Use of closures
This part