The easiest place to make mistakes in JavaScript is that closures are not going to run, technically, in JavaScript, every function is a closure because it always accesses data defined outside it. closures (Closure) are features that static languages do not have, and closures have the following characteristics:
A ① closure is a set of local variables for a function, except that these local variables will continue to exist after the function returns; ② Closures are just the "stacks" of functions that are not released after the function is returned, and we can also understand that these function stacks are not allocated on the stack but are allocated on the heap ③ A closure is generated when another function is defined within a function.
To better understand closures, let's take a look at a simple example:
var scope= "global"; function Outerfunc () { var scope = "Blog Park-flyelephant"; function Innerfunc () { console.log (scope);//Blog Park-flyelephant } innerfunc (); } Outerfunc (); Innerfunc ();//innerfunc is not defined
A nested function inside a function outside of a function is inaccessible, a function that is nested within a function is in the same variable scope as a variable defined inside a function, and the scope chain ranges from the same scope chain, and if the function content does not define a scope variable, the result of the final output should be " Global ". This is just the simplest form of closure, and if the closure is so simple, it won't be a problem in JavaScript.
For the above example, we have slightly modified:
var scope = "global"; function Outerfunc () { var scope = "Blog Park-flyelephant"; function Innerfunc () { console.log (scope);//Blog Park-flyelephant } return innerfunc; } Outerfunc () ();
The result of the final output is the value of the local variable, this point is more easily misunderstood because the function has been called to complete, the local variable should already not exist, the output should be "global", in fact, the function inside the nested function of the local variable existence reference, will maintain local variables, the professional point should be keep Alive
Believe this time you have a little bit of a feeling about closures, take a look at the classic examples:
function Constfuncs () { var funcs = []; for (var i = 0; i < i++) { Funcs[i] = function () { console.log (i); }; } return funcs; } var funcs = Constfuncs (); FUNCS[6] ();
According to our should be output is 6, but the result of the final output is 10, through the above example we know that the variables and our definition of the anonymous function is in the same scope, the anonymous function access is the final value of I, I the final value is 10, so the output is 10, single from this example may not feel, Look at the actual development examples we will understand a bit more deeply:
$ (function () { var eles=$ ('. Closure '); for (var i = 0; i < eles.length; i++) { eles[i].onclick=function () { alert (i);}} );
There is no doubt that regardless of which element the final output is the total number of elements, if we want to let the above example click on Funcs[6] () Output 6 is also possible, that is, each function has a corresponding local scope, see the following changes:
function Constfuncs () { var funcs = []; for (var i = 0; i < i++) { (function (i) { funcs[i] = function () { console.log (i); }; }) (i); } return funcs; } var funcs = Constfuncs (); FUNCS[6] ();
JavaScript also has a very important function is to hide the data, this plug-in package with more than the first to see a simple counter:
var counter = (function () { var count = 0; return function () { console.log (count); return count++;} ; } ()); Counter (); Counter ();
This output is 0, 1, not 0, 0, as for the reason at the end of the article will give an explanation, look at the updated version of the data package:
var db = (function () {///Create a hidden object, this object holds some data///from outside is unable to access this object's var data = {};//Creates a function that provides some way to access data from the method ret Urn function (key, Val) { if (val = = = undefined) {return Data[key]}//Get else {return Data[key] = val}//Set }//We can call this anonymous method//return this intrinsic function, which is a closure}) ();d B (' x '); Returns UNDEFINEDDB (' X ', 1); Set data[' x '] to 1db (' X '); Return 1//We cannot access the data object itself///But we can set its members
The trick here is to make the function an expression that calls execution immediately, and then keep the external variable through an intrinsic function, and if it doesn't call execution immediately, we'll find that each time it's a new function that doesn't hold the data state:
var counter = function () { var count = 0; return function () { console.log (count); return count++; }; Counter () (); Counter () ();
As for the function expression called immediately, some people call it the self-executing anonymous function (self-executing anonymous functions), in fact, there are more than 10 ways to write the function expression immediately, and we are usually left and right parenthesis two kinds:
(function () {Console.log (' 1 ');}) () ( function () {Console.log (' 2 ');} ())
Other ways of writing are as follows:
Either of the following, patterns can be used to immediately invoke//a function expression, utilizing the Functio N ' s execution context to//create "privacy." (function () {/* code */} ()); Crockford recommends this one (function () {/* code */}) (); But this one works just as well//Because the point of the parens or coercing operators are to disambiguate//Betwee n function expressions and function declarations, they can is//omitted when the parser already expects an expression (b UT please see the//"Important note" below). var i = function () {return 10;} (); True && function () {/* code */} (); 0, function () {/* code */} (); If you don ' ts about the return value, or the possibility of making//your code slightly harder to read, you can s Ave a byte by just prefixing//The function with a unary operator. !function () {/* code */} (); ~function () {/* code */} (); -function () {/* code */} (); +function () {/* code */} (); Here ' s anotherVariation, from @kuvos-i ' m not sure of the performance//implications, if any, of the using the ' new ' keyword, but it work S.//http://twitter.com/kuvos/status/18209252090847232 new function () {/* code */} new function () {/* code */} ()/// Only need parens if passing arguments
Reference Link: http://benalman.com/news/2010/11/immediately-invoked-function-expression/#iife
javascript-Closure Package