Closures (closure) are a very important threshold for mastering JavaScript from the human door to the deep, which is a difficult and characteristic of the JavaScript language, and many advanced applications rely on closures. Below, write down my study notes ~
Closures-everywhere
In front-end programming, the use of closures is very common, we often intentionally or unintentionally, directly or indirectly using the closure. Closures can make passing data more flexible (such as handling some click events)
! function () { var localdata = "Localdata here"; Document.addeventlistener (' click ', ////Handle the Click event using an external local variable, such as the localdatafunction here () { console.log (localdata);
Another example of the following: (is not very kind ~ ~)
! function () { var localdata = "Localdata here"; var url = "http://www.baidu.com/"; $.ajax ({ url:url, function() { // do sth ... Console.log (Localdata);}} );} ();
One more example of this is what we usually call closures.
function outer () { var localval =; return function () { return localval; var func = outer (); // -
In this example, call outer () returns an anonymous function (), which can access the local variable localval of outer (), and still have access to outer () after the outer () call is over, calling Func () again. The local variable Localval
The concept of closures
Closures, unlike general functions, allow a function to access a non-local variable when it is called outside of an immediate lexical domain. --Wikipedia
Closures are functions that can read other functions ' internal variables. --Ruan Yi Feng
Because in the JavaScript language, only sub-functions inside the function can read local variables, it is possible to simply interpret the closure as "a function defined inside a function".
So, in essence, a closure is a bridge that connects the inside of the function to the outside of the function.
Use of closures
This part is transferred from this blog post
Closures can be used in many places. Its maximum usefulness is two, one of the previously mentioned variables that can read the inside of a function, and the other is to keep the values of these variables in memory at all times.
function F1 () { var n=999; Nadd=function() {n+=1} function f2 () {alert (n); } return F2; } var result=// 999//
In this code, result is actually the closure F2 function. It runs altogether two times, the first value is 999, the second value is 1000. This proves that the local variable n in the function F1 is kept in memory and is not automatically cleared after the F1 call.
Why is that? The reason is that F1 is the parent function of F2, and F2 is assigned to a global variable, which causes F2 to always be in memory, and F2 's presence depends on F1, so F1 is always in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call ends.
Another notable part of this code is the line "nadd=function () {n+=1}", which first did not use the var keyword in front of Nadd, so Nadd is a global variable, not a local variable. Second, the value of Nadd is an anonymous function (anonymous functions), and the anonymous function itself is a closure, so nadd is equivalent to a setter that can manipulate local variables inside the function outside of the function.
Closures-Package
(function() { var_userid = 23492; var_typeid = ' item '; varExport = {}; functionConverter (userId) {return+userId; } export. getUserId =function() { returnConverter (_userid); } export. GetTypeId =function() { return_typeid; } window.export=Export; Output} () in this way); Export.getuserid (); //23492Export.gettypeid ();//ItemExport._userid;//undefinedExport._typeid;//undefinedExport.converter;//undefined
The closure feature allows us to encapsulate some complex function logic, in which the method (Getuserid,gettypeid) on the export is called to indirectly access the private variable in the function, but the direct call to Export._userid is impossible to get _userid. This is also the use of node inside the feature bar ~
Cyclic closure of common errors
In this case, we add 3 div, the value is AAA,BBB,CCC, we want to achieve is click on the AAA Output 1, click on the BBB Output 2, click on the CCC output 3
Document.body.innerHTML = "<div id=div1>aaa</div>" + "<div id=div2>bbb</div><div id=div3 >ccc</div> "; for (var i = 1; i < 4; i++) { document.getElementById (' div ' + i). AddEventListener (function() { // }); }
Results Click AAA,BBB or CCC are alert (4) ~ ~
The problem is that the value of I is already 4 when the initialization is complete .
To achieve what we want to click on the AAA Output 1, click on the BBB Output 2, click on the CCC output 3, to use the closure of the technique, in each loop, with the immediate execution of the anonymous function to wrap it up, this way, each alert (i) value is taken from the closure environment of I, This I come from the assignment of each cycle I can output a.
Document.body.innerHTML = "<div id=div1>aaa</div>" + "<div id=div2>bbb</div>" + "<div id= Div3>ccc</div> "; for (var i = 1; i < 4; i++) { ! function(i) {///② Use this parameter I, to getElementById () to refer to document.getElementById (' div ' + i). AddEventListener (function() { // * );} (i); ① to pass the value of the traverse to the anonymous function }
Study Questions
If you can understand the results of the following two sections of code, you should understand the operation mechanism of the closure. (from teacher Ruan) This topic summed up real second ~ ~
Code snippet one.
var name = "the window"; var object ="My object"function() { returnfunction
() { returnthis. Name; }; } }; Alert (Object.getnamefunc () ());
Code snippet two.
var name = "the window"; var object ="My object"function() { var This ; returnfunction() { return that.name; }; } }; Alert (Object.getnamefunc () ());
Deep understanding of JavaScript closures (Closure)