JavaScript closure mechanism __java

Source: Internet
Author: User
Tags closure garbage collection

Original address: http://www.felixwoo.com/archives/247

Reference: http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html


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:

<script>
function A () {
	var i = 0;
	Function B () {
		alert (++i);
	}
	return b;
}
var C = a ();
C (); Alert 1
C ();//Alert 2
</script>


1 Function b is nested within function A; This code has two features:

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 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.

(reprint please indicate the origin: http://www.felixwoo.com/archives/247)


second, the closure has any effect and effect.

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 the closure of the role of a very straightforward description, unprofessional and not rigorous, but you must be able to read. Understanding closures 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)

(reprint please indicate the origin: http://www.felixwoo.com/archives/247)


the microscopic world of closure

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.

3 when function A is defined, the JS interpreter sets the scope chain (scope chain) of function A to the "environment" where a is defined, and if a is a global function, only the window object in scope chain.

4 when the function A is executed, a will enter the corresponding execution environment (excution context).

5 in creating 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.

6 then the execution environment 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.

7 The next step is to add a arguments property on the active object that holds the arguments passed when the function A is invoked.

8 Finally, a reference to all function A's parameters and the internal function B is 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:

9 Search for its own active object, if present, return if it does not exist, and then search until it finds the active object that will continue searching for function A.

10 If a prototype prototype object exists in function B, it finds 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.

11 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:

<script>
function f (x) {
	var g = function () {
		alert (++x);
	}
	return g;
}
var h = f (1);
H (); Alert 2
h ();//Alert 2
</script>


· 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. The variable h in this code points to the anonymous function in F (returned by G).

· Suppose that the scope of function h is defined at definition, 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.

(reprint please indicate the origin: http://www.felixwoo.com/archives/247)


Four, closures the application scene

12 variable security within the protection 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.

13 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.

14 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

<script>
function Constructor () {
	var this = this;
	var membername = value;
	function MemberName (...) {...}
}
</script>


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

(reprint please indicate the origin: http://www.felixwoo.com/archives/247)


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.

(reprint please indicate the origin: http://www.felixwoo.com/archives/247)


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 indicate the origin: http://www.felixwoo.com/archives/247)


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.