JavaScript Closure Deep Understanding (closure) _javascript Tips

Source: Internet
Author: User
Tags closure garbage collection

One, what is closure?

The "official" explanation is that a closure is an expression (usually a function) that has many variables and an environment that binds them, and therefore these variables are also part of the expression.
I believe very few people can read this sentence directly, because he describes too academic. In fact, this phrase is in layman's terms:all function in JavaScript is a closure . In general, however, nested function results in a more powerful closure, which is what we call "closures" most of the time. Look at the following code:

Function a(0function B(alert(++i) returnb= a(); c ();

This code has two features:

    1. Function b is nested inside function A;
    2. function A returns function B.

The reference relationship is shown in figure:

So after the Var c=a () is executed, the variable C actually points to the variable i in the function b,b, then executes C () and pops up a window to display the value of I (for the first time 1). This piece of code actually creates a closure, why? Because the variable C outside function A refers to function B within function A, that is to say:

When the internal function B of function A is referenced by a variable outside of function A, we create a "closure" that we normally call "closures".

Let's talk a little more thoroughly. A "closure" is a method function in the constructor body that defines another function as the target object, and the method function of the object in turn refers to the temporary variable in the outer outer function body. This makes it possible to indirectly maintain the value of the temporary variables used by the original constructor body as long as the target object retains its method throughout its lifetime. Although the first constructor call has ended, the name of the temporary variable disappears, but the value of the variable is always referenced within the target object's method, and the value can only be accessed through this method. Even if you call the same constructor again, but only new objects and methods are generated, the new temporary variable only corresponds to the new value, and the last time the call was separate.

To get a deeper understanding of closures, let's continue to explore the effects and effects of closures.

What is the function and effect of closure?

In short, the function of a closure is that after a is executed and returned, the closure makes the JavaScript garbage collection mechanism GC not reclaim the resource occupied by a, because the execution of the internal function B of a relies on the variables in a. This is a very straightforward description of the closure function, unprofessional and not rigorous, but the general meaning is that, understand the closure requires a step-by-step process.
In the above example, because the closure makes function a return, I always exist in a, so each C (), I is the value of alert out I after 1.

So let's imagine the other case, if a returns a function B, the situation is completely different. Since A is executed, B is not returned to the outside of a, but is referenced by a, while a is only referenced by B, so functions A and B refer to each other without being disturbed by the outside world (referenced by the outside world), and functions A and B are recycled by GC. (The garbage collection mechanism for JavaScript is described later in detail)

Third, closure of the microcosm

To get a deeper understanding of the relationship between closures and function A and nested function B, we need to introduce several other concepts: the execution Environment for functions (excution context), active objects (call object), scope (scope), scope chain. Use function A as an example to illustrate these concepts from the process of definition to execution.

    1. When the function A is defined , the JS interpreter sets the scope chain (scope chain) of function A to the "Environment" whereA is defined, and if a is a global function, the scope There are only window objects in the chain.
    2. When the function A is executed , a will enter the corresponding execution Environment (excution context).
    3. When you create an execution environment, you first add a scope property, the scope of a, whose value is the scope chain in step 1th. That is, the scope chain of the a.scope=a.
    4. The execution environment then creates an active object (Call object). The active object is also an object that has attributes, but it does not have a prototype and is not directly accessible through JavaScript code. After the active object is created, the active object is added to the top of the scope chain of a. At this point A's scope chain contains two objects: A's active object and a Window object.
    5. The next step is to add a arguments property on the active object that holds the arguments passed when the function A is invoked.
    6. Finally, the reference of all function A and the internal function B are added to the active object of a. In this step, the definition of function B is complete, so as in step 3rd, the scope chain of function B is set to the environment defined by B, that is, the scope of a.

In this, the entire function A is completed from the definition to the execution step. At this point a returns the reference of function B to C, and the scope chain of function B contains a reference to the active object of function A, which means that B can access all the variables and functions defined in a. Function B is referenced by C, function B is dependent on function A, so function A is not reclaimed by GC after it returns.

When function B is executed it will be similar to the above steps. Therefore, the scope chain of B at execution time contains 3 objects: The active object of B, the active object of a, and the Window object, as shown in the following illustration:

As shown in the figure, when accessing a variable in function B, the search order is:

    1. Searches for its own active object, if it exists, returns if it does not exist, and then searches until it finds the active object that will continue searching for function A.
    2. If a prototype prototype object exists in function B, it looks for its own prototype object after searching for its own active object, and then continues to find it. This is the variable lookup mechanism in JavaScript.
    3. Returns undefined if the entire scope chain is not found.

In this paragraph, two important words are mentioned: the definition and execution of functions. It is mentioned that the scope of the function is defined at the time of defining the function, rather than being determined at the time of execution (see steps 1 and 3). Use a piece of code to illustrate the problem:

function f(x(returnx returng= f(1)alert(H());  

The variable h in this code points to the anonymous function in F (returned by G).

    • Assuming that the scope of function h is determined by execution alert (h ()), then H's scope chain is the active object->window object->alert the active object of H.
    • It is assumed that the scope of the function h is defined, that is, the anonymous function that H points to defines the scope. Then, at the time of execution, H's scope chain is: H's active object->f the active object->window object.

If the first hypothesis is established, the output value is undefined; if the second assumption is true, the output value is 1.

The results of the operation prove that the 2nd hypothesis is correct, stating that the scope of the function is indeed defined when defining the function.

Four, closures the application scene

    1. Protect variable security within a function. Take the first example, in function A, I have only function B to access, and I cannot access it through other means, thus protecting the security of I.
    2. Maintain a variable in memory. As in the previous example, because of the closure, function A has always been in memory, so every time C () is executed, I will add 1 to my self.
    3. Through the protection of the security variables to achieve JS private properties and private methods (can not be external access) Recommended reading:http://javascript.crockford.com/private.html
      Private properties and methods cannot be accessed outside of constructor

      Function Constructor(.....) this= valuefunction membername(...). {... }

The above 3 points are the most basic application scenarios for closures, and many classic cases derive from this.

Five, JavaScript garbage collection mechanism

In JavaScript, if an object is no longer referenced, the object is reclaimed by GC. If two objects are referenced to each other and are no longer referenced by the 3rd, then the two referenced objects are also reclaimed. Because function A is referenced by B, B is referenced by C outside of a, which is why function A is not recycled after it executes.

Six, the conclusion

Understanding JavaScript closures is the way to advanced JS programmers, understanding their interpretation and operational mechanisms to write more secure and elegant code. If you have any suggestions and questions about this article, please leave a message. Reprint please famous source.

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.