Simple analysis of JavaScript closures in encapsulation functions _javascript tips

Source: Internet
Author: User
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 ~ ~ ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.