Deepen understanding of the concept of JavaScript closure

Source: Internet
Author: User
I have read a lot of information about the JavaScript closure (closure) on the Internet, most of which are written

I have read a lot of information about JavaScript closures on the Internet, most of which are very academic and professional. For beginners, don't understand closures, and even the text descriptions are hard to understand. The purpose of this article is to use the most popular text to uncover the true face of the JavaScript closure.

1. What is a closure?

The official explanation is that a closure is an expression (usually a function) with many variables and an environment bound to these variables. Therefore, these variables are part of the expression. I believe that few people can directly understand this sentence, because he described it too academic. In fact, all functions in JavaScript are closures. But in general, nested functions produce more powerful closures, which are also called "closures" in most cases ". See the following code:

function a() {var i = 0;    function b() {        alert(++i);    }    return b;}var c = a();c();

This code has two features:

  1. Function B is nested in function;
  2. Function a Returns function B.

Reference relationship

In this way, after var c = a () is executed, variable c actually points to function B, variable I is used in B, and then c () is executed () then a window will pop up showing the I value (the first time is 1 ). This Code actually creates a closure. Why? Because variable c outside function a references function B in function a, that is:When function a's internal function B is referenced by a variable outside function a, a closure is created ".

Let's be more thorough. The so-called "closure" refers to defining another function in the constructor as the method function of the target object, and the method function of this object references temporary variables in the outer function body in turn. This allows the target object to indirectly retain the temporary variable value used by the original constructor as long as it can maintain its method throughout the lifetime. Although the call to the initial constructor has ended, the name of the temporary variable has also disappeared, but the value of the variable can always be referenced in the method of the object, this value can only be accessed in this way. Even if the same constructor is called again, only new objects and methods are generated. The new temporary variables only correspond to new values, which are independent of those called last time.

To better understand closures, let's continue to explore the functions and effects of closures.

2. What are the functions and effects of closures?

In short, the function of the closure is that after a executes and returns, the closure makes the garbage collection mechanism of Javascript GC not to reclaim the resources occupied by, because the execution of the internal function B of a depends on the variables in. This is a straightforward description of the function of the closure. It is neither professional nor rigorous, But you can understand it. The process of understanding the closure needs to be gradual.

In the above example, because of the existence of the closure, the I in a always exists after function a returns, so that each execution of c (), I is the value of alert after auto-increment 1.

Then let's imagine another situation. If a does not return function B, the situation is completely different. Because after a is executed, B is not returned to the external world of a, but is referenced by a. At this time, a will only be referenced by B, therefore, functions a and B are referenced by each other without being disturbed by the outside world (referenced by the outside world), and functions a and B are recycled by GC.

3. Micro-world of closures

To learn more about closures and the relationship between function a and nested function B, we need to introduce several other concepts: the function execution environment (excution context), and the activity object (call object) scope and scope chain ). The process from definition to execution of function a is used as an example to describe these concepts.

  1. When defining function a, the js interpreter sets the scope chain of function a to the "Environment" where a is located when defining function a. If function a is a global function, the scope chain contains only window objects.
  2. When function a is executed, a enters the corresponding execution environment (excution context ).
  3. In the process of creating the execution environment, a scope attribute is first added for a, that is, the scope of a, and its value is the scope chain in step 1. That is, the scope chain of a. scope =.
  4. Then, the execution environment creates a call object ). An activity object is also an object with attributes, but it does not have a prototype and cannot be directly accessed through JavaScript code. After creating the activity object, add the activity object to the top of the scope chain of. In this case, the scope chain of a contains two objects: The activity object of a and the window object.
  5. The next step is to add an arguments attribute to the activity object, which stores the parameters passed when calling function.
  6. Finally, all the form parameters of function a and the reference of internal function B are added to the activity object of function. In this step, the definition of function B is completed. As in step 1, the scope chain of function B is set to the environment defined by B, that is, the scope of function.

At this point, the steps from definition to execution of function a are completed. At this time, a returns the reference of function B to function c, and the scope chain of function B contains the reference to the activity object of function, that is to say, B can access all variables and functions defined in. Function B is referenced by Function c, and function B is dependent on function a. Therefore, function a is not recycled by GC after return.

When function B is executed, it will be the same as the above steps. Therefore, during execution, B's scope chain contains three objects: B's activity object, a's activity object, and window object, as shown in:

When accessing a variable in function B, the search order is:

  1. Search for its own activity object first. If it exists, return. If it does not exist, search for the activity object of function a until it is found.
  2. If function B has a prototype object, search for its own prototype object after searching for its own activity object. This is the Variable Search Mechanism in Javascript.
  3. If the entire scope chain cannot be found, undefined is returned.

This section describes two important words: function definition and execution. The scope of the function is determined when the function is defined, rather than when the function is executed (see steps 1 and 3 ). Use a piece of code to illustrate this problem:

function f(x) {    var g = function () { return x; }    return g;}var h = f(1);alert(h());

In this Code, the variable h points to the anonymous function in f (returned by g ).

  • Assume that the scope of function h is determined by the execution of alert (h (), then the scope chain of h is: h activity object-> alert activity object-> window object.
  • Assume that the scope of function h is determined during definition, that is, the anonymous function pointed to by h has already determined the scope. During execution, the scope chain of h is: h activity Object> f activity Object> window object.

If the first hypothesis is true, the output value is undefined. If the second hypothesis is true, the output value is 1. The running result proves that the 2nd assumptions are correct, indicating that the function scope is indeed determined when the function is defined.

4. Application scenarios of closures
  1. Protect the security of variables in the function. Taking the initial example as an example, in function a, I can only access function B, but cannot access function B through other channels, thus protecting the security of I.
  2. Maintain a variable in the memory. Still, for example, because of the closure, the I in function a is always in the memory, so each execution of c () will add 1 to the I self.
  3. By protecting the security of variables, JavaScript private attributes and private methods (cannot be accessed externally) are recommended. Read: http://javascript.crockford.com/private.html and conor.
function Constructor(...) {    var that = this;    var membername = value;    function membername(...) {...}}

The above three points are the most basic application scenarios of closures. Many classic cases are based on this.

5. Garbage collection mechanism of JavaScript

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 no longer referenced by 3rd, the two objects referenced by each other will be recycled. Because function a is referenced by function B and function B is referenced by Function c outside of function a, this is why function a is not recycled after execution.

6. Conclusion

Understanding the closure of JavaScript is the only way to move towards a senior JavaScript programmer. Only by understanding its interpretation and running mechanism can we write safer and more elegant code.

This article is available at http://www.nowamagic.net/librarys/veda/detail/92.

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.