The code information comes from http://ejohn.org/apps/learn/.
Self-executing, temporary, function
(function() { var count = 0
This is a simple self-executing anonymous function.
Make a click Count
Document.addeventlistener ("Click", (functionvar numclicks = 0return function ++false);
The key code is the self-executing anonymous function, which returns a function that triggers the function by clicking on it, and, depending on the closure scope chain, can access the variable Numclick from which the anonymous function was executed.
Why are the values the same?
for var d = 0; D < 3; d++ ) setTimeout (function() { console.log (d); // 2 // 2 // 2 }, 200);
At 200ms, the anonymous function runs three times, depending on the scope chain, which references D, when the external for has already been looped, and D is 3.
How can I output normally?
for var d = 0; D < 3; d++) (function(d) { setTimeout(function() { console.log (d);
0
1
); }) (d);
The anonymous function referenced here is actually the parameter of the self-executing function, the function executes three times, is independent of each other, and the received parameter is 0,1,2 in turn. This is a typical use of self-executing functions.
Anonymous functions are useful when packaging libraries.
(function() { varfunction() { // }; // })();
When developing a library, we do not affect the global namespace. Using self-executing anonymous functions is a good thing to sit on, making the variables inside the library private, and optionally providing an interface for external variables.
Another way of writing
var mylib = (function() { function mylib () { // } // return mylib;}) ();
JavaScript advanced Knowledge Point--staging scope