JavaScript---Closures and scope chains

Source: Internet
Author: User
Tags closure

Scope and scope chain:

Reference article: http://www.cnblogs.com/malinlin/p/6028842.html

Http://www.cnblogs.com/lhb25/archive/2011/09/06/javascript-scope-chain.html

http://www.zhangyunling.com/?p=134

Summarize:

①js are objects everywhere.

An execution environment and variable object are created when the ② function executes

③ code runs in the execution environment variable objects are stored sequentially into the scope chain

④ executes a function once creates a new active object, there is a new scope chain, and multiple scope chains do not interfere with each other.

The ⑤ reference function does not disappear, the active variable persists, the reference variable points to null after the closure has been used, and the memory is freed.

1 scope (global scope)
(1) The outermost function and the variables defined outside the outermost function have global scope
(2) All variables that do not have a direct assignment defined are automatically declared as having global scope
(3) The Properties of all window objects have global scope, such as Window.name, window.location as follows: The global function is pointed to in the timer

   setTimeout ("C ()", +) = =  setTimeout ("this.") C () ", +)

  

1 varA = 1;2 functionB () {3     varA = 2;4SetTimeout ("C ()", 1000);5SetTimeout (c,2000);6     functionC () {7Alert ("A=" +a);8     }9 }Ten functionC () { OneAlert ("A=" +a); A } -B ();


2 Scope (local scope)
Local scopes are generally accessible only within a fixed code fragment, most commonly such as inside a function

1. Execution Environment and Activity objects

The function generates execution environment and variable objects at execution time, and a scope chain (scope chain) of the variable object is created when the current code executes in an execution environment.

  The execution Environment (execution context) defines other data that a variable or function has access to, and each execution environment has a variable object associated with it (variable object). Variables and functions defined in the execution environment are stored in this variable object;
The global execution environment is one of the outermost execution environments and is often considered a window object
After all the code in the execution environment is executed, the execution environment is destroyed, and the variables and functions stored therein are destroyed; (The global execution environment is destroyed when the app exits).

In the case of a closure, each time a function is executed, an activity variable and an execution environment of a are generated, and after execution, the execution environment of a is destroyed, but the active object is still preserved because it is referenced by the closure function, so the reference variable is pointed to null after the closure is exhausted .


3. Scope chain (Scope Chain)
When code executes in an execution environment, a scope chain (scope chain)of the variable object is created, and the scope chain is used to specify the order of access for all variables and functions that the execution environment has access to, and when a function is created, Its scope chain is populated with data objects that can be accessed by creating the scope of this function.

The most front-end of the scope chain, which is always the variable object of the current code execution Environment , and if the environment is a function, its active object is the variable object
The next variable object of the scope chain, from the outer containment environment, then the next variable object, from the next outer containment environment, and so on until the global execution environment
In the function execution process, the variable is looked up to layer by level according to the scope chain of the current execution environment, and the identifier is parsed

These values are copied into the scope chain of the run-time context, in the order in which they appear in the function. Together they form a new object called the "Activation Object", which contains all the local variables, named arguments, parameter sets, and this of the function, which is then pushed into the front of the scope chain, and the active object is destroyed when the run-time context is destroyed.

During the execution of a function, no variable is encountered, and an identifier parsing process is passed to determine where to get and store the data. The process from the scope chain head, that is, starting from the active object search, find an identifier of the same name, if found to use this identifier corresponding to the variable, if not found to continue to search the scope chain of the next object, if the search all objects are not found, the identifier is considered undefined. Each identifier undergoes such a search process during the execution of the function. As you can see from the structure of the scope chain, the deeper the identifier is in the scope chain of the run-time context, the slower the read and write speed will be. When writing code, you should use as few global variables as possible, and use local variables as much as you can. A good rule of thumb is that if a cross-scope object is referenced more than once, it is stored in a local variable before it is used.

Closures:

1. Closures can access variables in the function.

2. You can keep variables in memory for long periods of time. But closures can not be abused, otherwise it will lead to memory leaks, affecting the performance of the Web page. When the closure is exhausted, use the resource immediately and point the reference variable to null.

<script>functionA () {varx = 1; return function() {x++;        Console.log (x); }    }    varM1 = A ();//execute a function for the first timeM1 ();//2M1 ();//3    varm2 = A ();//second execution of a functionM2 ();//2M1 ();//4</script>

1. (Why is the value of x incremented when the M1 is executed consecutively?)
Answer: The value of x has been incremented because M1 has not been released in the referenced activity object A (you can let m1=null if you want to release it).
2. When defining the function m2, why does the value of X start again from 1?
Answer: Because a function is run again, a new active object is generated for a, so the scope chain of the M2 refers to a new X value.
Why is x in 3.m1 and M2 independent of each other and maintained?
Answer: Because when you define M1 and M2, a function is run, and two active objects are generated, so the scope chain of M1 and M2 is the active object that points to a different a.

OK, here's a look at the knowledge points mentioned earlier:

Execution environment and variable objects are generated when a function is run
After all the code in the execution environment is executed, the execution Environment is destroyed, and the variables and functions stored therein are destroyed; (Global execution environment to destroy when application exits)

Closures Common topics:

  

1 functionF1 () {2       varn=999;3Nadd=function() {N+=1}4       functionF2 () {5 alert (n);6 }7       returnF2;8 }9     varresult=F1 ();TenResult ();//999 One Nadd (); First, the VAR keyword is not used 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, AResult ();//1000

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 garbage collected after the call ends (garbage Collection) recycling.

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.

The point of this in the closure:

  

var name = "the window"; var object = {    "My object",        function() {        return function () {            returnthis. name;};}    ; document.write (Object.getnamefunc ());// The execution Environment of an anonymous function is global, so its this object usually points to the window

JavaScript---Closures and scope chains

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.