But I use JavaScript often, so I need to understand the concepts involved.
In fact, the concept of closure in JavaScript is very simple, that is, the function uses external variables and can be obtained without passing parameters.
For example:
<script> <br>var sMessage = "Hello world"; <br>function sayHello(){ <br>alert(sMessage); <br>} <br>sayHello(); <br>addNumber(1,2); <br> <br>var iBaseNum = 10; <br>function addNumber(iNum1, iNum2) { <br>function doAddition() { <br>alert(iNum1 iNum2 iBaseNum); <br>} <br>return doAddition(); <br>} <br>function a(){ <br>var i=0; <br>function b(){ <br>alert( i); <br>} <br>return b; <br>} <br>var c = a(); <br>c(); <br>c(); <br><br></script>
The first function sayHello is not passed Parameters directly use the sMessage variable, which is called a closure.
The second function is more complicated. There is a doAddition in it which is also a closure function. It does not require parameters and directly obtains iNum1, iNum2 and the external variable iBaseNum in the execution environment.
The third function can protect the access of the i variable, and always save i in the memory, and can continue to increase. (A classic use of closures)
The closure in jquery is similar, let’s give an example first
You may ask
(function($){
$("div p").click(function(){alert("cssrain!") });
})(jQuery); //A closure
How to write this?
Don’t worry, I also asked the upc for advice, and then I understood a little bit.
The $ here is just a formal parameter, but jquery is a global variable, so it will be executed automatically without calling the function, or it can be converted into a normal function in two steps. Write the function first and then call it.
As shown below
Actually:
( function($){
$("div p").click(...);
})(jQuery);
is equal to
function tempFunction($){ //Create a function with $ as formal parameter
$("div p").click(....);
}
TempFunction(jQuery); //Pass in the actual parameters jQuery to execute the function.
Just do it directly Write it this way, forget it
(function(cssrain ){
cssrain("div p").click(.... );
})(jQuery); //A closure
closure Basic writing method:
(function(){do someting})();
//You can understand this as defining an anonymous function and executing it immediately
With parameters, it is like this:
(function( Formal parameter){do someting})(actual parameter);
In addition
(function(){var upc="i am upc"})();
alert(upc);
Yes Prompt undefined.
Because after closure, the variables inside are equivalent to local.
Benefits of closure:
No additional global variables are added.
All variables during execution are inside the anonymous function.
The above example is not very good and is a bit confused with JavaScript closures, but it is indeed a closure in jquery. It's just processed by jquery.
If there is anything wrong, please discuss it with each other. I am also a beginner and there are still many things I don’t understand.