But I always use JavaScript, so I have to understand the concept.
In fact, the concept of closure in JavaScript is very simple, that is, the function to use external variables, do not need to pass the reference can be obtained.
As an example:
Copy Code code 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 A () {
var i=0;
Function B () {
alert (++i);
}
return b;
}
var C = A ();
C ();
C ();
</script>
The first function, SayHello, uses the smessage variable without passing parameters, which is called a closure.
The second function is complex, there is a doaddition is also a closure function, he does not need parameters, directly in the execution environment to obtain inum1,inum2, as well as external variable ibasenum.
The third function is the ability to protect the access to the I variable and keep I in memory and can always increase. (a classic use of closures)
In jquery, the closure is similar, let's give an example
You might ask.
Copy Code code as follows:
(function ($) {
$ ("div p"). Click (function () {alert ("cssrain!")});
}) (JQuery); A closed bag
What is this writing?
Don't worry, I also consulted the UPC, just a little understand.
The $ in this is just a formal parameter, but jquery is a global variable, so you don't need to call the function to do it automatically, or in two steps
is to convert to a normal function, write the function first, then call.
As shown below
In fact:
Copy Code code as follows:
(function ($) {
$ ("div p"). Click (...). );
}) (JQuery);
is equal to
Copy Code code as follows:
function Tempfunction ($) {///create a functional with $ as parameter
$ ("div p"). Click (...)
}
Tempfunction (JQuery); Incoming argument jquery execution function.
Just write it straight, forget it.
Copy Code code as follows:
(function (Cssrain) {
Cssrain ("div p"). Click (...);
}) (JQuery); A closed bag
The basic wording of closure:
(function () {do someting}) ();
This is what you would understand to define an anonymous function and execute it immediately.
With parameters, that's it:
(function (formal parameter) {do someting}) (argument);
Other than that
(function () {var upc= "I am UPC"}) ();
Alert (UPC);
will prompt undefined.
Because after the closure, the variables inside are equivalent to the local.
The benefits of closures:
Without adding additional global variables,
All variables are inside the anonymous function during execution.
The example above is not very good, a bit confusing with javascript closures, but it's also a kind of closure in jquery. It's just processed by jquery.
If there is anything wrong, we discuss each other, I am also a beginner, there are many do not know where.