The code section used in closures is referenced in the public classes of the people's Valley and the hungry, thank you.
1. What is a closure?
A closure refers to the function of a lexical representation of a variable that is not evaluated, that is, a function can use a variable defined outside the function .
To better understand the closure, in addition to the form itself, but also to understand: JS has no block-level scope; JS's memory recovery mechanism (visible JavaScript scope).
2. Examples of closures
A closure is a structure that getname references an external variable name to form a closure. Line 9th assigns name to the variable whoname so that name remains in memory. If there is no getname to form a closure, the people function is executed and its name variable is freed.
1 function people () { 2 var name = ' Xiaohua '
3. Bugs that can be easily caused by closures
var result = []; function foo () { var i = 0; for (; i<3;i++) { function() { alert (i); } } } Foo (); result[// ////
This is because I is always present, there is no block-level scope, I is finally equal to the I in all functions in the 3,result array pointing to the I that equals 3. The solution is to pass arguments to the function.
4. Several uses of closures
JS has no block-level scope, but it has a function scope. To make no naming conflicts between variables, use an immediate execution function to isolate the scope. The name in the following two scopes does not affect each other, inadvertently forming the structure of the closure. If there is no isolation scope
1(function(){2 varname = ' AA ';3 4 functionA () {5 returnname;6 }7 })();8 9(function(){Ten varname = ' BB '; One A functionA () { - returnname; - } the})();
1 varCounter =function(){2 varCount = 0;3 return function(){4 return++count;5 };6 };7 8 varCountadd = counter ();//function () {return ++count;};9Countadd ();//1TenCountadd ();//2 OneAlert (Countadd ());//3
- Declaring private variables
JS itself does not have private variables, public variables, static variables, are simulated implementation. If you use name as a property of people, you cannot implement private.
1 varPeople = (function(){2 varName = "Xiaohua";3 functionpeople () {};4People.prototype = {5GetName:function(){6 returnname;7 },8SetName:function(newName) {9Name=NewName;Ten } One }; A returnpeople; - })(); - the varp =NewPeople ();
A probe into JavaScript closures