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:
The code is as follows:
The first function sayHello does not pass parameters and directly uses the sMessage variable. This 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 closures in jquery are similar, let’s give an example first
You may ask
The code is as follows:
(function($){
$(“p p”).click(function( ){alert(“cssrain!”)});
})(jQuery); //A closure
What is this way of writing?
Don’t worry, I also asked 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 call it later.
As shown below
Actually:
The code is as follows:
(function($){
$(“p p”).click(…);
})(jQuery);
It is equal to
The code is as follows:
function tempFunction($){ //Create a function with $ as formal parameter
$(“p p”).click(….);
}
TempFunction(jQuery); // Pass in the actual parameters jQuery executes the function.
Just write it like this, forget it
The code is as follows:
(function(cssrain){
cssrain(“p p”).click(…. );
})(jQuery); //A closure
The basic way to write a closure:
(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);
Also
(function(){var upc=”i am upc”})();
alert(upc);
will prompt undefined.
Because after closure, the variables inside are equivalent to local.
Benefits of closures:
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 anything goes wrong, please discuss it with each other. I am also a beginner and there are still many things I don’t understand.