But I often use JavaScript, so I need to understand the concept here.
In fact, the closure concept in Javascript is very simple, that is, the function uses external variables and can be obtained without passing parameters.
For example:
CopyCode The Code is as follows: <SCRIPT>
VaR smessage = "Hello World ";
Function sayhello (){
Alert (smessage );
}
Sayhello ();
Addnumber (1, 2 );
VaR ibasenum = 10;
Function addnumber (inum1, inum2 ){
Function doaddition (){
Alert (inum1 + inum2 + ibasenum );
}
Return doaddition ();
}
Function (){
VaR I = 0;
Function B (){
Alert (++ I );
}
Return B;
}
VaR c = ();
C ();
C ();
</SCRIPT>
The first function sayhello does not transmit parameters. It directly uses the smessage variable, which is called a closure.
The second function is complex. There is a doaddition which is also a closure function. It does not need parameters and gets inum1, inum2, and the external variable ibasenum in the execution environment.
The third function can protect the access to the I variable and keep saving I in the memory, which can be increased all the time. (A classic use of closures)
Closure in jquery is similar. Let's give an example first.
You may askCopy codeThe Code is as follows: (function ($ ){
$ ("Div P"). Click (function () {alert ("cssrain! ")});
}) (Jquery); // a closure
What is the writing method?
Don't worry. I also consulted UPC to understand it a little.
$ Here is only a form parameter, but jquery is a global variable, so it will be automatically executed without calling this function, or in two steps
Is to convert to a normal function, first write the function, then call.
As shown below
Actually:Copy codeThe Code is as follows: (function ($ ){
$ ("Div P"). Click (...);
}) (Jquery );
Is equalCopy codeThe Code is as follows: function tempfunction ($) {// create a function with $ as the parameter
$ ("Div P"). Click (....);
}
Tempfunction (jquery); // input the real parameter jquery to execute the function.
Simply write it like this. Forget it.
Copy code The Code is as follows: (function (cssrain ){
Cssrain ("Div P"). Click (....);
}) (Jquery); // a closure
basic writing of closures:
(function () {do someting })();
// define an anonymous function and execute it immediately
with parameters:
(function (parameter) {do someting }) (Real parameter);
In addition
(function () {var UPC = "I am UPC"}) ();
alert (UPC );
the message "undefined" is displayed.
the variables in the closure are equivalent to local variables.
advantages of closure:
no additional global variables are added.
during execution, all variables are inside the anonymous function.
the above example is not very good, and it is a bit confusing with the closure of JavaScript, but it is indeed a closure in jquery. It's just processed by jquery.
if there is anything wrong with it, we will discuss it with each other. I am also a beginner, and there are many other things I don't know.