WBKT2T recently discovered a new term: closures. (oneself behind, want to study well only), Baidu, Google looked at the principle and examples, but also understand the strong closure. jquery also carried out the closure, some of the online personal development of the framework is the closure of the function. Know the closure of the principle and use of distribution, so they have a small test, with doubts: the use of closures what good? What happens when you don't use it? Write down the following code, but also hope that we give younger brother some answers
Using closures:
Instance 1
Copy Code code as follows:
var $Darren;
(function () {
var obj={version: "1.0", Author: "Darren"};
Obj.add=function (ARG1,ARG2) {
return (ARG1+ARG2);
}
Obj.multi=function (ARG1,ARG2) {
return (ARG1*ARG2);
}
$Darren =obj;
})(); anonymous function, and make it execute immediately
Alert ($Darren. ADD (6,2)); Result 8
Alert ($Darren. Multi (3,5)); Result 15
Do not use closure code:
Instance 2
Copy Code code as follows:
var $Darren 2={version: "1.0", Author: "Darren"};
$Darren 2.add=function (ARG1,ARG2) {
return (ARG1+ARG2);
}
$Darren 2.multi=function (ARG1,ARG2) {
return (ARG1*ARG2);
}
Alert ($Darren 2.Add (6,2)); Result 8
Alert ($Darren 2.Multi (3,5)); Result 15
My understanding is that:
The use of closures can prevent naming conflicts, as in instance 1, if the $darren variable conflict needs to be changed only two places, and in instance 2, if the $DARREN2 variable conflict (here is 3)
. After you use closures, you can use the internal functions even if the anonymous function completes.
And I have a doubt:
Why do we all recommend Example 1, instance 1 and instance 2 which is better and why? Functions that can be implemented as well.
I hope you can point to the younger brother, this understanding is correct?
What else is there to add.
Thank you all ~ ~ ~