The _javascript techniques of scope chain and closure in JavaScript

Source: Internet
Author: User
Tags closure
Scope
Global scope
Local scope
Scope chain
Execution context
Active Object
Closed Bag
Closure optimization

There is a concept in JavaScript that has not been learned before--closures. What is closure? A closed package from a superficial understanding is related to the scope. So, before you say closure, talk about scopes.

Scope (SCOPE)

Generally speaking, the variables and functions used in a piece of program code are not always available, the scope that limits its usability is scoped, the use of scope enhances the locality of program logic, enhances the reliability of the program, and reduces the name conflict.

Global scope (SCOPE)

Objects that can be accessed anywhere in your code have global scope, and the following scenarios have global scope:

1. The outermost function and variables defined outside the outermost function have global scope, for example:
Copy Code code as follows:

var outside= "var outSide";
function Outfunction () {
var name= "var inside";
function Insidefunction () {
alert (name);
}
Insidefunction ();
}
alert (outSide); That's right
alert (name); Error
Outfunction (); That's right
Insidefunction ()///Error

2. A variable that does not define a direct assignment is automatically declared to have a global scope, for example:
Copy Code code as follows:

Blogname= "Csdn Li da"

3. The properties of all window objects have global scope, for example: the built-in properties of Window objects all have global scope, such as Window.name, window.location, window.top, etc.

Local scope (global scope)
Copy Code code 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 (scope chain)

In JavaScript, everything in JavaScript is an object, including a function. function objects, like other objects, have properties that can be accessed through code and a series of internal properties that are accessible only to the JavaScript engine. One of the internal properties is the scope, which contains the set of objects in the scope of the function being created, called the scope chain of the function, which determines which data can be accessed by the function.
When a function is created, its scope chain is populated with data objects that are accessible in the scope of this function creation. For example, a function:
Copy Code code as follows:

function Add (num1,num2) {
var sum = num1 + num2;
return sum;
}

When the function add is created, its scope chain fills in a global object that contains all the global variables, as shown in the following illustration (note: The picture illustrates only a subset of the variables):


Thus, the scope chain of a function is created when a function is created.

Execution contexts (Execute context)

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

Copy Code code as follows:

var total = Add (5,10);

When the Add function is executed, JavaScript creates an execute context, which contains all the information required for the runtime of the Add function. The execute context also has its own scope chain, and when the function is run, the JavaScript engine first initializes the scope chain of execution contexts from the scope chain of the Add function.

Active object (Active object)

The JavaScript engine then creates an active object, which is copied into the scope chain of the run-time context in the order in which they appear in the function, and together they form a new object-"active object (Activation object)", This object contains all the local variables, parameters, and this variable for the runtime of the function, which are pushed into the front of the scope chain, and the active object is destroyed when the runtime context is destroyed. The new scope chain is shown in the following illustration:

The execution context is a dynamic concept that, when the function is run, is also a dynamic concept that is referenced by the scope chain of the execution context, and can be concluded that the execution context and the active object are dynamic concepts. And the scope chain of the execution context is initialized by the function scope chain.
During the execution of the function, each time a variable is encountered, it retrieves where the data is fetched and stored, from the scope chain head, that is, from the active object, to find an identifier with the same name, if it is found, to use the variable for that identifier, and if not, to continue searching for the next object in the scope chain, If all objects are not found, the identifier is not defined, and each identifier undergoes such a search process during function execution.
Closure (closure)
Let's take a look at an instance of JavaScript code:
Copy Code code as follows:

<script type= "Text/javascript" >
function Newload () {//new page loaded event
for (var i = 1; I <=3; i++) {
var anchor = document.getElementById ("anchor" + i); Find each anchor
Anchor.onclick = function () {//Add click event for anchor
Alert ("You clicked Anchor" +i)//Give a click response
}
}
}
Window.onload = Newload; Assign the Newload event to the page load
</script>

Foreground code:
Copy Code code 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>

Run Result: No matter click that anchor, always pops up Anchor4, and we have no anchor4 at all:

When we load the page, the Newload function in JavaScript is already running, and by the loop we know that anchor has been assigned a value of 4. But with previous programming experience, local variables are destroyed when they are used, but anchor is not, and it is obvious that JavaScript is in another way.

Closure in JavaScript is actually a function that is created during the runtime of a function, and when the above function is executed, a closure is created, and the closure references the anchor in the Newload scope. Here's how JavaScript implements closures: When executing the Newload function, the JavaScript engine creates the scope chain of the Newload function execution context, which contains the active object for the Newload execution, and The JavaScript engine also creates a closure, and the closure's scope chain also references the active object of the newload, so that when the newload executes, the execution context and the active object have released the anchor, but the closure still references the Newload active object , so click on the display is "you clicked Anchor4". Operating period as shown:

Closure Optimization

Now that the closures appear and we don't want to see the results, we need to optimize it. Optimized JavaScript (other invariant):

Copy Code code as follows:

<script type= "Text/javascript" >
function Newload () {//new page loaded 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 click event for anchor
Alert ("You clicked Anchor" + i); Give a click reaction
}
}
Window.onload = Newload; Assign the Newload event to the page load
</script>

Run Result: prompt for corresponding hint information

Result analysis: The result of the optimization is that we separate the declared variable from the Click event. Explain the scope chain explained in the above: page load, the first execution of the listener function, and the listener function requires the anchor variable, in the Listener function scope chain does not, will go to the next level of the scope chain, that is, to find the anchor in the Newload, Because the listener has already been determined which anchor click corresponds to which message, so just look for the corresponding anchor in the newload, not wait for the loop to produce Anchor4.

Because it's a short time to touch JavaScript, it's a place where you understand the error.

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.