JS closure (reproduced + spliced)

Source: Internet
Author: User
Tags keep alive

1. What is a closure?
The official explanation is:A closure is an expression (usually a function) that has many variables and is 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, this sentence is as follows: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 section.Code:

Function (){
VaR I = 0;

Function B (){
Alert (++ I );
}
Return B;
}
VaR c = ();
C ();
This code has two features:

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

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" isDefine 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.. 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 a closure is,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, which is neither professional nor rigorous, but probably means that 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. (The garbage collection mechanism of JavaScript will be described in detail later)

Iii. microview 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 excution context, call object, scope, and scope chain of a function ).The process from definition to execution of function a is used as an example to describe these concepts.

When defining function A, the JS interpreter sets the scope chain of function a to define the "Environment" of function A. If function a is a global function, the scope chain contains only window objects.
When function a is executed, a enters the corresponding execution environment (excution context ).
When creating an execution environment,First, a scope attribute is added for A, that is, the scope of.The value is the scope chain in step 1. That isA. Scope = scope chain of.
Then the execution environment willCreate an activity 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 the activity object is created,Add the activity object to the top of the scope chain of. At this time, the scope chain of A contains two objects:Activity object and window object of.
The next step isAdd an arguments attribute to the activity object, which stores the parameters passed when function a is called.
Finally, add the parameters of all function a and the reference of function B 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.
Iv. application scenarios of closures
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.
1. Maintain a variable in the memory. It is still like a closure,The I in function a always exists in the memory. Therefore, each execution of C () will add 1 to the I.
2. Implement JS private attributes and private methods (not externally accessible) by protecting the security of variables. Read the following link for more information:Http://javascript.crockford.com/private.html
3. Private attributes and methods cannot be accessed outside the constructor.

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.

 

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

Vi. Conclusion

Understanding the closure of JavaScript is moving towards Advanced JSProgramOnly by understanding its interpretation and operating mechanism can we write safer and more elegant code.

For details, refer:Http://www.jb51.net/article/24101.htm###

 

When a function is nested in a function, the internal function can access the variables in the external function.

Function Foo (x ){
VaR TMP = 3;
Function bar (y ){
Alert (x + y + (++ TMP ));
}
Bar (10 );
}
Foo (2 );
Alert 16 will be executed no matter how many times, because bar can access the foo parameter X and the foo variable TMP.

However, this is not a closure. When you return an internal function, it is a closure. The internal function will close-over the variable of the external function until the internal function ends.

Function Foo (x ){
VaR TMP = 3;
Return function (y ){
Alert (x + y + (++ TMP ));
}
}
VaR bar = Foo (2); // bar is now a closure
Bar (10 );
The above script will eventually use alert 16, because although bar is not directly in the internal scope of Foo, bar can still access X and TMP.

However, because TMP still exists inside the bar closure, it will still add 1, and every time you call bar, it will add 1.

The above X is a nominal value (value transfer), which is the same as other nominal values in JS. When foo is called, the value of the real parameter X is copied, the copied copy is used as the foo parameter X.

Then the problem arises. When processing objects in JS, the reference is used for transmission. Therefore, when you call Foo, an object is passed. The closure of the foo function return will also reference the original object!

Function Foo (x ){
VaR TMP = 3;
Return function (y ){
Alert (x + y + TMP );
X. memb = x. memb? X. memb + 1: 1;
Alert (X. memb );
}
}
VaR age = new number (2 );
VaR bar = Foo (AGE); // bar is now a closure that references age
Bar (10 );
Unexpectedly, Every time bar (10) is run, X. memb will automatically add 1. However, note that X points to the same object variable -- age every time. After bar (10) is run twice, age. memb will change to 2.

This is related to memory leakage of HTML objects. However, it seems to be out of the answer range.

Johnmerlino told Ali:

Here is an example of a closure without the return Keyword:

Function closureexample (OBJ, text, timedelay ){
SetTimeout (function (){
Document. getelementbyid (objid). innerhtml = text;
}, Timedelay );
}
Closureexample ('mydiv ', 'Closure is created', 500); late at John pick:

Functions in JS can access them:

1. Parameters

2. Local variables or functions

3. external variables (Environment Variables ?), Including

3.1 global variables, including dom

3.2 External function variables or functions.

If a function accesses its external variables, it is a closure.

Note that external functions are not required. By accessing external variables, a closure can maintain these variables (keep alive. In the example of internal and external functions, external functions can create local variables and exit. However, if any one or more internal functions do not exit after they exit, the internal function maintains the local data of the external function.

A typical example is the use of global variables.

Mykhal replied:

Wikipedia defines closures as follows:

In computer science, a closure is a function together with a referencing environment for the nonlocal names (free variables) of that function.

Technically, in JS, every function is a closure, because it can always access data defined externally.

Since scope-defining construction in Javascript is a function, not a code block like in your other ages, what we usually mean by closure in Javascript is a fuction working with nonlocal variables defined in already executed surrounding function.

Closures are often used to create functions that contain hidden data (but not always like this ).

VaR DB = (function (){
// Create a hidden object that holds some data
// The object cannot be accessed from outside
VaR data = {};
// Create a function that provides methods to access data
Return function (Key, Val ){
If (val = undefined) {return data [Key]} // get
Else {return data [Key] = Val} // set
}
// We can call this anonymous method
// Returns this internal function, which is a closure.
})();
DB ('x'); // return undefined
DB ('x', 1); // set data ['X'] to 1
DB ('x'); // returns 1
// We cannot access the data object itself.
// But we can set its members.
After reading the answers from so many foreign experts, I don't know whether you understand it or not. I understand it anyway.

 

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.