Home  >  Article  >  Web Front-end  >  Simple analysis of JavaScript closures when encapsulating functions_javascript skills

Simple analysis of JavaScript closures when encapsulating functions_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:41:041005browse

wbkt2t recently discovered a new term: closure. (I am lagging behind, so I have to study hard). After looking at the principles and examples on Baidu and Google, I also understood the power of closures. JQuery has also promoted closures, and some personally developed frameworks on the Internet have used closures. After knowing the principle and use of closures, I tried it a little, with doubts: What are the benefits of using closures? What are the consequences of not using it? I wrote the following code, and I hope you can give me some answers
Use closures:
Example 1

Copy code The code is 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

Does not use closure code:
Example 2
Copy code The code is as follows:

var $Darren2={version:"1.0",author:"Darren"};
$Darren2.Add= function(arg1,arg2){
return (arg1 arg2);
}
$Darren2.Multi=function(arg1,arg2){
return (arg1*arg2);
}
alert($Darren2.Add(6,2)); //Result 8
alert($Darren2.Multi(3,5)); //Result 15

Mine The understanding is:
. Using closures can prevent naming conflicts. For example, in Example 1, if the $Darren variable conflicts, only two places need to be changed, while in Example 2, if the $Darren2 variable conflicts, multiple changes are needed. (Here are 3 places)
. After using a closure, even if the anonymous function is executed, you can still use its internal functions.

I also have a question:
Why does everyone recommend the writing method of Example 1? Which one is better, Example 1 or Example 2, and why? The same functions can be achieved.

I hope everyone can give me some advice, is this the right understanding?
Anything else to add?
Thank you everyone~~~
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn