Cliché JavaScript closures

Source: Internet
Author: User
Tags closure variable scope

A closure refers to a function that has access to a variable in another function scope.
--The third edition of the Advanced JavaScript program

My first understanding of closures comes from the "senior three", first of all only through the "right" two words we can further infer. Under normal circumstances, one function is "not authorized" to access variables in the scope of another function.

First, what is a variable

So when talking about closures , review the special variable scope of JavaScript.
The scope of a variable is nothing more than two kinds: global variables and local variables . Here are a few simple examples to show the difference between a global variable and a local variable .

1. Global variables
var str = "hello chedabang";console.log(str);function test(){ console.log(str);}test();

The results of the controlled table:
hello chedabang
hello chedabang
This indicates that the variable str can be accessed directly outside the function, and can be accessed by the function to the variable. Since everyone has access to this variable, it means that the variable declared outside the function body is a global variable .

2. Local Variables
function test1(){    var str1 = "hello chedabang"; console.log(str);}test1();

Console output Results:
hello chedabang
One more set of code.

function test1(){    var str1 = "hello chedabang";}console.log(str1);

Console output Results:
Uncaught ReferenceError: str1 is not defined
One more set of code.
This indicates that the variable str1 can only be used by its own function, and when called outside of the function because there is no access to the function test1 () variable, so the console error "variable undefined." So we can infer that the variables declared inside the function are local variables .
It is important to note that if you use VAR to declare a variable inside a function, the variable is not a local variable , but a global variable .

function test2(){    var str2 = "hello world"; console.log(str2);}console.log(str2);

Console output Results:
hello chedabang
hellow chedabang

Summary:

1. Global Variables can be read directly inside the function
2, outside the function can not directly read the local variables inside the function

Second, how to access the local variables inside the function from the outside

For a variety of reasons, we sometimes need to get local variables within the function. However, as already mentioned, normally this is not accessible.

function zhugeliang(){                     //诸葛亮 var str3 = "蜀国"; function adou(){ console.log(str3); //阿斗 }}var simayi = zhugeliang(); simayi(); //控制台报错 司马懿攻不下蜀国

This code can be seen, because the function of Zhuge Liang is created in their own functions of the local variable "Shu", so Sima Yi want to get to var str3 = "Shu"; that will be an error, the reactive.
People who have read the Three Kingdoms should know that Zhuge Liang is known as Wolong. But in the face of fools so always can't afford mediocrity, also can only beyond resurrection, Shu finally still not able to unified Three kingdoms, but fools fell a reluctant laughingstock.

Simayi (Sima Yi) Gets the code for the internal variable "shu":
 function zhugeliang (//Zhuge Liang var str3 = " Shu "; function adou ( console.log (STR3); //Fools} return Adou;} var Simayi = Zhugeliang (); Simayi (); //console Output "Shu" Sima Yi get shu           

Thinking Analysis:
The function "Fools" is wrapped inside the function "Zhuge Liang", when all local variables inside "Zhuge Liang" are visible to "fools". But the reverse is not possible, "fools" inside the local variables, "Zhuge Liang" is not visible. This is the JavaScript-specific "chain-scoped" structure (chain scope), where child objects look up the variables of all the parent objects one level at a level. Therefore, all the variables of the parent object are visible to the child object, and vice versa.
Therefore, since "fools" can read "Zhuge Liang" in the local variables, so long as the "fools" as the return value, you can read the "Zhuge Liang" outside its internal variable "Shu".

Three, the simple concept of closure

The fools function in the previous section of the code is the closure.
Used to go online to check the various professional literature on the "closure" (closure) definition is very abstract, it is difficult to read.
So my personal understanding is that closures are functions that can read other functions ' internal variables.
Because in the JavaScript language, only sub-functions inside the function can read local variables, it is possible to simply interpret the closure as "a function defined inside a function".
So in essence, a closure is a secret path that joins the inside of the function and the outside of the function, and constructs it.

Dikes Yixue, the function fortress collapsed in the closure.

Iv. use of closures

Closures can be used in many places. Its maximum usefulness is two, one of the previously mentioned variables that can read the inside of a function, and the other is to keep the values of these variables in memory at all times.
How to understand this sentence? Take a look at the following code.

 function f1 () {var n = 999;NADD = function (1}function f2 ( Span class= "Hljs-params") {console.log (n);} return F2;} var result=f1 (); result (); //999nAdd (); result (); //            

In this code, result is actually the closure F2 function. It runs altogether two times, the first value is 999, the second value is 1000. This proves that the local variable n in the function F1 is kept in memory and is not automatically cleared after the F1 call.
Why is that? The reason is that F1 is the parent function of F2, and F2 is assigned to a global variable, which causes F2 to always be in memory, and F2 's presence depends on F1, so F1 is always in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call ends.
Another notable part of this code is the line "nadd=function () {n+=1}", which first did not use the var keyword in front of Nadd, so Nadd is a global variable, not a local variable. Second, the value of Nadd is an anonymous function (anonymous functions), and the anonymous function itself is a closure, so nadd is equivalent to a setter that can manipulate local variables inside the function outside of the function.

V. Note points for using closures

1, because the closure will make the function of the variables are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page, in IE may lead to memory leaks. The workaround is to remove all unused local variables before exiting the function.
2. The closure will change the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, and the closure as its public method, and the internal variable as its private property (private value), be careful not to arbitrarily change the value of the inner variable of the parent function.

Above is my understanding of the function closure , insufficient hope also please enlighten.
PS: In addition, the article for reference to the three cases, just to facilitate the interpretation of cases to ridicule, if there are offensive views of the three fans, please forgive me.

Cliché JavaScript closures

Related Article

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.