The following 2 brackets () will be executed immediately
(/*// recommended to use this
(/*/// But this is also available.)
As with normal function execution of the time parameters, self-executing functions of the expression can also be such a parameter, because the closure can directly refer to the parameters passed in, using these locked parameters, self-executing function expression can effectively save the state.
//This code is wrong, because the variable i has never been back locked live
//Instead, when the loop is executed, I get the value when we click
//Because this time I do really get the value
//So whether you click on that connection, the final display is I am link #10 (if there are 10 a elements)
var elems = document.getElementsByTagName (' a ');
for (var i = 0; i < elems.length; i++) {
Elems[i].addeventlistener (' click ',Function (e) {
E.preventdefault ();
Alert (' I am link # ' + I);
}, ' false ');
}
//This is available because he is inside the self-executing function expression closure
//The value of I is present as an index of locked, and after the loop execution is completed, although the value of the last I becomes the total number of a elements (for example, 10)
//But the Lockedinindex value inside the closure is unchanged, because he's done it.
//So when you click Connect, the result is correct.
var elems = document.getElementsByTagName (' a ');
for (var i = 0; i < elems.length; i++) {
(function (Lockedinindex) {
Elems[i].addeventlistener (' click ',Function (e) {
E.preventdefault ();
Alert (' I am Link # ' + lockedinindex);
}, ' false ');
}) (i);
}
You can also apply a self-executing function expression to a handler function as follows
not outside of the AddEventListener.
but relatively speaking, the above code is more readable
var elems = document.getElementsByTagName (' a ');
for (var i = 0; i < elems.length; i++) {
Elems[i].addeventlistener (' Click ', (function (lockedinindex) {
return function (e) {
E.preventdefault ();
Alert (' I am Link # ' + lockedinindex);
};
}) (i), ' false ');
}
JS self-executing function expression