Understanding of JS Closures

Source: Internet
Author: User
Tags variable scope

When it comes to closures , this is a feature that JS has to mention, and many traditional languages do not have such features, such as Java C and so on.

Before reading, always understand what is the closure of the package! Here's a sketch of a schematic to understand:

To understand closures, you must first understand the special variable scope of JavaScript.

The scope of a variable is nothing more than two kinds: global variables and local variables.

The special point of the JavaScript language is that the global variables can be read directly inside the function.

Basically all programming languages have similar characteristics, and local methods can access the properties of external parent class methods, that is, subclasses or child methods can access the resources of the parent class.

        <!--in a normal script, a method can get external variables, or global variables--        var num = one;        function Func1 () {            console.log (num);        }        Func1 ();

So the above code, we can get the value to Num.

Can the parent class get the value inside the child method?

                function Func2 () {            var num1 =;            num2 =;        }        Func2 ();        <!--Console.log (NUM1);  will be an error! --        Console.log (num2) <!--can get the value to num2 because the default is a global variable when you do not use Var to define variables--

Of course, it is not possible, because the variable scope of the sub-method is only the scope of the sub-method, external is not available.

  

So how can we get the local variables of the sub-methods externally?

In the case of Java, a private property of a class can be obtained through a public get method, such as:

Class person{  private String name;  Public String GetName () {    return name;    }    }

In this way, you can get a private property inside a class, and in the same way, in JS, you can get the local variable of the method by a method, and then read the desired variable value through the method in this method.

        function func3 () {            var num3 =;            function Func4 () {                return num3;            }            return func4;        }        var func = func3 ();        Console.log (func ());

Refer to the following illustration:

Local variables inside the func3 cannot be obtained externally, but local methods inside the func3 Func4 can be obtained, so a func4 reference is returned so that the internal variables of the FUNC4 can be obtained externally through this func3.

Although it is a circle, but in the outside of the method through such a means to obtain the internal value.

The local method in this method Func4 is called closure, according to a lot of book concept, this method constructs the method inside and the method exterior bridge, makes outside also can arbitrarily obtain to the method internal resources.

But closures can cause variables to persist in memory, so there will be some performance problems, preferably not easy to use, even if the use of the appropriate actual release.

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.

JS Code

1    functionF1 () {2 3       varn=999;4 5Nadd=function() {N+=1}6 7       functionF2 () {8 alert (n);9 }Ten  One       returnF2; A  - } -  the     varresult=F1 (); -  -Result ();//999 -  + Nadd (); -  +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. (GC Explanation: In JavaScript, if an object is no longer referenced, the object will be recycled by GC.) If two objects are referenced by each other and are no longer referenced by the 3rd, then the two mutually referenced objects are also recycled. Because function A is referenced by B and B is referenced by a c outside of a, this is why function A is not recycled after execution. )

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.

Let's look at one more example

JS Code

functionvar a =0; alert (a);  } var a=4; Outerfun (); alert (a) ;

The result is 0,4. Because the VAR keyword is used inside a function to maintain the scope of a within outfun ().

Then look at the following code:

JS Code

function//   a =0; alert (a);  } var a=4; Outerfun (); alert (a) ;

The result is 0, 0 is really strange, why?

A scope chain is a term that describes a path that can be used to determine the value of a variable. When a=0 is executed, the assignment is linked to Var a=4 along the scope, because the VAR keyword is not employed; and change its value.

Source code for the sample:

<!doctype html>

Operation Result:

JS Closure Understanding

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.