in the previous article about we mentioned the concept of closures in the JavaScript this keyword article. closures are functions that have access to variables in another function scope. The ability to access external variables (references, updates) from function objects is one of the conditions that make up a closure. A common way to create closures is to create another function inside one function. To understand closures, first look at what is the life cycle of a variable.
The declaration period of a variable is the lifetime of the variable, and relative to the scope that represents the visible scope of the variable in the program, the concept of life cycle refers to how long a variable can exist and can be accessed within a range of periods. Take a look at the following example:
Functionextent () {var n = 0; return function () {n++; Console.log ("n=" + N); };} var Returnfun = extent (); Returnfun (); "N=1" Returnfun (); "N=2"
The local variable n is declared in the extent function, which belongs to the local variable in the outer scope and is enclosed inside by the function object. The life of the closed variable is the same as the life cycle of the function object that encloses it, i.e. the closure extends the declaration period of the local variable.
The concept of closure is more abstract, to go back and forth repeatedly is that one sentence, not good understanding, the following mainly through a few examples to see how to use closures.
1. First example: using closures in a loop
<!-- javascriptsnippet_1 begin -->function createfunction () { var result = []; for (var i = 0; i < 10; i++) { result[i] = function () { return i; }; } return result;};/ /Call result[0] (); //9result[1] (); //9... ...result[9] (); // 9<!-- javascriptsnippet _1 end --> <!-- JavaScriptSnippet_2 Begin -->function Createfunction () { var result = []; for (var i = 0; i < 10; i++) { (function (num) { result[i] = function () { return num; };}) (i); &nbSP;} return result;} Call Result[0] (); //0result[1] (); //1... ...result[9] (); //9<!-- javascriptsnippet_2 End --> <!-- javascriptsnippet_3 begin -->function createfunction () { var result = []; for (var i = 0; i < 10; i++) { result[i] = (function (num) { return function () { return num; }; }) (i); } return result;} Call Result[0] (); //0result[1] (); //1... ...result[9] (); //9<!-- javascriptsnippet_3 End --> <!-- javascriptsnippet_4 begin -->function createfunction () { var result = []; for (var i = 0; i < 10; i++) { result[i] = (function (num ) { return function () { return num; }; } (i)); } return result;} Call Result[0] (); //0result[1] (); //1... ...result[9] (); //9<!-- javascriptsnippet_4 End --> <!-- javascriptsnippet_5 begin -->function createfunction () { var result = []; for (var i = 0; i < 10; i++) { result[i] = function (num) { return function () { return num ; }; } (i); } Return result;} Call Result[0] (); //0result[1] (); //1... ...result[9] (); //9<!-- javascriptsnippet_5 End -->
2. the second example: Once again, consider the closure with the example of a
<!-- html begin--><pid= "Help" >helpful notes will appear here</p ><p>e-mail: <input type= "text" id= "email" name= "Email" ></p><p>name: <input type= "text" id= "name" name= "name" ></p><p>age: <input type= "text " id=" Age " name=" ></p><!-- HTML End--><!--Javascript common snippet begin -->function showhelp (Info) { document.getelementbyid (' Help '). Innerhtml =info;} For later calls Function closurefunc (info) { return function () { showhelp (info); };} Function setuphelp () { var helpText = [ {id: " Email ", info: " please input youremail address "}, {id: " Name ", info: " Please input your name "}, {id: "Age", info: "Please input your age"} ]; <!-- JavaScript Common Snippet End --> <!-- javascript Snippet_1 Begin --><!-- can not -->for (var i = 0; i < helptext.length; i++) { var item = helpText[i]; document.getelementbyid (item.id). Onfocus = function () { showhelp ( Item.info); }}<!-- JavaScript Snippet_1 End --> <!-- javascript snippet_2 begin --><!-- can -->for (var i = 0; i < helptext.length; i++) { var item = helpText[i]; document.getelementbyid (item.id). Onfocus = closurefunc (Item.info);} <!--&NBSP;JAVASCRIPT&NBSP;SNIPPET_2&NBSP;END&Nbsp;--> <!-- JavaScript Snippet_3 Begin --><!-- can -->for ( var i = 0; i < helptext.length; i++) { (function (num) { var item = helpText[num]; document.getElementById (item.id). Onfocus = function () { ShowHelp (item.info); }; }) (i); <!-- JavaScript Snippet_3 End --> <!-- JavaScript Snippet_4 begin --><!-- can -->for (var i = 0; i < helptext.length; i++) { var item = helpText[i]; document.getElementById (item.id) .onfocus = (function (info) { return function () { showhelp (info); }; }) (Item.info);} <!-- JavaScript Snippet_4 End --> <!-- JavaScript Snippet_5 begin --><!-- can -->for (var i = 0; i < helptext.lenght; i++) { var item = helpText[i]; document.getElementById (item.id) .onfocus = ( function (info) { Return function () { showhelp (info); }; } (Item.info) );} <!-- JavaScript Snippet_5 End --> <!-- JavaScript Snippet_6 begin --><!-- can -->for (var i = 0; i < helptext.length; i++) { var item = helpText[i]; document.getElementById (item.id). Onfocus = function (Info) { return FunctIon () { showhelp (info); }; } ( Item.info);} <!-- javascript snippet_6 end -->}setuphelp ();
Code Snippet 6 can also be successful, but it is recommended that you enclose it in parentheses, which is recommended in the form of code Snippet 4 or code fragment 5 . If you write this directly in JavaScript:
Function (info) {return function () {showHelp (info); };} (Item.info);
causes an error, because JavaScript treats the function keyword as the beginning of a declaration of functions, and the function declaration cannot be followed by parentheses, but the function expression can be followed by parentheses. To convert a function declaration to a function expression, simply add a pair of parentheses to it as follows:
(function (info) {return function () {showHelp (info); };}) (Item.info);
3. Third example: Creating a public method access private variable
var counter = (function () { var privateCounter = 0; Var changeby = function (val) { privateCounter += val; }; return { getcounter: function () { return privateCounter; }, Setcounter: function (Newcounter) { privateCounter = Newcounter; }, increment: function () { changeby (1); }, decrement: function () { changeby ( -1); } };}) ();//Call Counter.privatecounter //undefinedcounter.getcounter (); //0counter.setcounter (100); Counter.getcounter (); //100counter.increment (); COunter.getcounter (); //101counter.decrement (); Counter.getcounter (); //100 //transformation to factory class Var makecounter = function () { Var privatecounter = 0; var changeby = function (val) { privateCounter += val; }; return { getcounter: function () { return privateCounter; }, setcounter: function (Newcounter) { privateCounter = newCounter; }, Increment: function () { changeby (1); }, decrement: function () { changeby (-1); } };};/ /Generate and Invoke Var counter_1 = makecounter (), &Nbsp; counter_2 = makecounter (); Counter_1.getcounter (); //0counter_2.getcounter (); //0counter_1.setcounter (88); Counter_2.getcounter (); //0
4. Fourth Example: impersonation of block-level scopes
in Java ,C and Many other programming languages have the concept of block-level scope, in Java as an example:
for (int i = 0; i<; i++) {//do something}system.out.println (i); I cannot be resolved to a variable
There is no block-scoped concept in JavaScript, such as:
for (var i = 0; i<; i++) {//do Something}var i;console.log (i); 10var i = 5;console.log (i); 5
In many cases, in order to not pollute the global namespace, you can use closures to simulate block-level scopes:
(function () {var just_a_number = 100; Console.log (Just_a_number); (); Console.log (just_a_number);//uncaught Referenceerror:just_a_number is not defined
So much to say about closures, the weight of understanding.
Finish.
reference / extension information:
the JavaScript Advanced Programming ( version 3 ) Nicholas c.zakas Translator: Lisongfeng Tianhua
http://www.zhihu.com/question/19554716
Http://www.cnblogs.com/dolphinX/archive/2012/09/29/2708763.html
Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Closures
http://bonsaiden.github.io/JavaScript-Garden/zh/#function. Closures
This article is from the "barrel of fake dog excrement" blog, please be sure to keep this source http://xitongjiagoushi.blog.51cto.com/9975742/1672553
Closures in JavaScript (Closure)