Scope chains and closures in JavaScript

Source: Internet
Author: User

Scope
GLOBAL SCOPE
Local Scope
Scope chain
Execution Context
Activity object
Closure
Closure Optimization

A previously unknown concept-closure emerged in JavaScript. What is a closure? On the surface, it is a closed package, which is related to the scope. Therefore, we should talk about the scope before talking about the closure.

Scope)

Generally, variables and functions used in a piece of program code are not always available. The scope of availability is the scope. The use of the scope improves the locality of the Program Logic and enhances the reliability of the program, reduce name conflicts.

Global Scope)

Objects that can be accessed anywhere in the Code have a global scope. The following situations have a global scope:

1. the outermost function and variables defined outside the outermost function have a global scope. For example:Copy codeThe Code is as follows: var outSide = "var outside ";
Function outFunction (){
Var name = "var inside ";
Function inSideFunction (){
Alert (name );
}
InSideFunction ();
}
Alert (outSide); // correct
Alert (name); // Error
OutFunction (); // correct
InSideFunction () // Error

2. undefined variables that directly assign values are automatically declared to have a global scope. For example:Copy codeThe Code is as follows: blogName = "CSDN Lida"

3. All properties of the window object have a global scope. For example, the built-in properties of the window object have a global scope, such as window. name, window. location, and window. top.

Local Scope)Copy codeThe Code is as follows: <span style = "font-family: SimSun;"> function outFunction (){
Var name = "inside name ";
Function inFunction (){
Alert (name );
}
InFunction ();
}
Alert (name); // Error
InFunction (); // error </span>

Scope chain)

In JavaScript, everything in JavaScript is an object, including a function. Function objects, like other objects, have attributes that can be accessed by code and a series of internal attributes that are only accessible by the JavaScript engine. An internal attribute is the scope, which contains the set of objects in the scope created by the function. It is called the scope chain of the function and determines which data can be accessed by the function.
After a function is created, its scope chain will be filled with accessible data objects in the scope of the function. For example:Copy codeThe Code is as follows: function add (num1, num2 ){
Var sum = num1 + num2;
Return sum;
}

When the function add is created, its scope chain is filled with a global object, which contains all global variables, as shown in (Note: The image only lists part of all variables):


It can be seen that the function scope chain is created when the function is created.

Execute context)

The scope of function add will be used during execution, for example:

Copy codeThe Code is as follows: var total = add (5, 10 );

When the add function is executed, JavaScript creates an Execute context, which contains all the information required during the runtime of the add function. Execute context also has its own Scope chain. When a function is running, the JavaScript engine first initializes the Scope chain of the execution context by using the Scope chain of the add function.

Active Object)

The JavaScript engine then creates an Active Object. These values are copied to the scope chain of the runtime context in the order they appear in the function, they form a new object, activation object, which contains all the local variables, parameters, and such variables during the function runtime, this object will be pushed to the frontend of the scope chain. When the runtime context is destroyed, the activity object will also be destroyed. Shows the new scope chain:

Execution context is a dynamic concept. When a function is created during operation, the Active Object of the activity Object is also a dynamic concept. It is referenced by the scope chain of the execution context and can be concluded: the execution context and the activity object are both dynamic, and the execution context's scope chain is initialized by the function scope chain.
During function execution, each variable is used to retrieve and store data from where it is obtained. This process searches for identifiers with the same name from the scope chain header, that is, from the activity object, if the variable corresponding to the identifier is found, the next object in the scope chain will be searched. If no object is found, the identifier is considered undefined, during function execution, each identifier must undergo such a search process.
Closure (closure)
Let's take a look at an example of javascript code:Copy codeThe Code is as follows: <script type = "text/javascript">
Function newLoad () {// create a page load event
For (var I = 1; I <= 3; I ++ ){
Var anchor = document. getElementById ("anchor" + I); // find each anchor
Anchor. onclick = function () {// Add a click event for anchor
Alert ("you clicked anchor" + I); // click response
}
}
}
Window. onload = newLoad; // assign the newload event to the page for loading.
</Script>

Front-end code:Copy codeThe Code is as follows: <body>
<A id = "anchor1" href = "#"> anchor1 </a> <br/>
<A id = "anchor2" href = "#"> anchor2 </a> <br/>
<A id = "anchor3" href = "#"> anchor3 </a> <br/>
</Body>

Running result: No matter which anchor is clicked, anchor4 is always displayed, and we do not have anchor4 at all:

When we load the page, the newLoad function in javascript has been run, and the loop shows that anchor has been assigned a value of 4. However, from the previous programming experience, partial variables will be destroyed after use, but anchor does not. Obviously, JavaScript adopts another method.

A closure is actually a function in JavaScript. It is created during the function runtime. When the preceding function is executed, a closure is created, which references anchor in the newLoad scope. Next let's take a look at how JavaScript implements the closure: When the newLoad function is executed, the JavaScript engine will create the scope chain of the newLoad function execution context, this scope chain contains the activity objects during newLoad execution. At the same time, the JavaScript engine will create a closure, and the scope chain of the closure will also reference the activity objects of newload, when newload is executed, although anchor has been released for both the execution context and the activity object, the closure still references the activity object of newload, therefore, click "you clicked anchor4 ". Runtime

Closure Optimization

Since the closure shows the result we don't want to see, we need to optimize it. Optimized javascript (Other unchanged ):

Copy codeThe Code is as follows: <script type = "text/javascript">
Function newLoad () {// create a page load event
For (var I = 1; I <= 3; I ++ ){
Var anchor = document. getElementById ("anchor" + I); // find each anchor
Listener (anchor, I); // listener Function
}
}
Function listener (anchor, I ){
Anchor. onclick = function () {// Add a click event for anchor
Alert ("you clicked anchor" + I); // click response
}
}
Window. onload = newLoad; // assign the newload event to the page for loading.
</Script>

Running result: a prompt message is displayed.

Result Analysis: the optimized result is that the declared variables are separated from the click event. Use the scope chain explained above to explain: when loading a page, the listener function is executed first, while the listener function requires the anchor variable, which is not in the listener function scope chain and will enter the next level of scope chain, find anchor in newLoad, because the listener has determined which anchor to click the corresponding prompt information, so it is just to find the corresponding anchor in newload, will not wait until the cycle is complete to generate anchor4.

It takes a short time to contact javascript. If you have any mistakes, please correct them.

Related Article

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.