Scoped chains and closures in JavaScript

Source: Internet
Author: User

scoped chains and closures in JavaScript2012-06-29 11:41 1878 people read reviews ($) Collection report

There is a concept in JavaScript that has not been learned before--closures. What is closure? The enclosing package, which is understood from the surface, is related to the scope. So, talk about the scope before closing the packet.

Scope (SCOPE)

Generally speaking, the variables and functions used in a program code are not always available, the scope of its availability is scoped, scope is used to improve the localization of the program logic, enhance the reliability of the program, reduce the name conflict.

Global scope (Globals scope)

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

1. The outermost function and the variables defined outside the outermost function have global scope, for example:

[JavaScript]View Plaincopyprint?
  1. <span style="FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;"  >var outside="var outSide";
  2. function Outfunction () {
  3. var name="var inside";
  4. function Insidefunction () {
  5. alert (name);
  6. }
  7. Insidefunction ();
  8. }
  9. alert (outSide); //Correct
  10. alert (name); //Error
  11. Outfunction (); //Correct
  12. Insidefunction () //Error </span>

2. Variables that do not have a direct assignment defined are automatically declared to have global scope, for example:

[JavaScript]View Plaincopyprint?
    1. <span style="FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >blogname="Csdn li da" </span>
3. The properties of all window objects have global scope, for example: The built-in properties of the Window object have global scope, such as Window.name, window.location, window.top, etc.

Local scope (local scope)

[JavaScript]View Plaincopyprint?
  1. <span style="FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >function outfunction () {
  2. var name="Inside name";
  3. function Infunction () {
  4. alert (name);
  5. }
  6. Infunction ();
  7. }
  8. alert (name); //Error
  9. 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 by the JavaScript engine. One of the internal properties is scope, which contains a collection of objects in the scope of the function being created, called the function's scope chain, which determines which data can be accessed by the function.
When a function is created, its scope chain is populated with data objects that can be accessed by creating the scope of this function. For example, a function:

[JavaScript]View Plaincopyprint?
    1. <span style="FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >function Add (num1,num2) {
    2. var sum = num1 + num2;
    3. return sum;
    4. }</span>

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

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

Execution contexts (Execute context)

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

[JavaScript]View Plaincopyprint?
    1. <span style="FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >var total = Add (5,10);</span>

When the Add function is executed, JavaScript creates an execute context (the execution contexts), and the execution context contains all the information needed to run the Add function. The execute context also has its own scope chain, and when the function runs, the JavaScript engine starts by initializing the scope chain of the execution context from the scope chain of the Add function.

Active objects (active object)

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

The execution context is a dynamic concept that is created when the function is run, the active object is also a dynamic concept, it is referenced by the scope chain of the execution context, and it can be concluded that both 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 a function, each time a variable is encountered, it retrieves from where the data is fetched and stored, from the scope chain head, that is, starting from the active object, looking for an identifier with the same name, if a variable corresponding to the identifier is found, and if not, continues to search for the next object in the scope chain. If all objects are not found after searching, the identifier is considered undefined, and each identifier undergoes such a search process during function execution.

Closures (closure)

Let's look at an example, JavaScript code:

[JavaScript]View Plaincopyprint?
  1. <span style="FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" > <script type="Text/javascript" >
  2. function Newload () { //New page loaded event
  3. For (var i = 1; I <=3; i++) {
  4. var anchor = document.getElementById ("anchor" + i); //Find each anchor
  5. Anchor.onclick = function () {//Add click event for anchor
  6. Alert ("You clicked Anchor" +i); Give a click Response
  7. }
  8. }
  9. }
  10. Window.onload = Newload; //Assign the Newload event to the page load
  11. </script></span>
Front Code: [HTML]View Plaincopyprint?
  1. <span style="FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><body>
  2. <a id="Anchor1" href="#">anchor1</a><BR />
  3. <a id="Anchor2" href="#">anchor2</a><br/>
  4. <a id="Anchor3" href="#">anchor3</a><BR />
  5. </body></span>
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 has finished running, and the loop in it shows that the anchor has been assigned a value of 4. However, from previous programming experience, local variables are destroyed when they are used, but anchor does not, and it is obvious that JavaScript is used in another way.

Closures in JavaScript is actually a function that is created during the function run time, and when the above function is executed, a closure is created, and the closure references the anchor in the Newload scope. Here's a look at how JavaScript implements closures: When executing the Newload function, the JavaScript engine creates a scope chain of the Newload function execution context, which contains the active object at Newload execution time, and The JavaScript engine also creates a closure, and the scope chain of the closure refers to the active object of newload, so that when Newload executes, the execution context and the active object are freed anchor, but the closure refers to the active object of the Newload. , so click to show "You clicked Anchor4". Operating period

Closure optimization

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

[JavaScript]View Plaincopyprint?
  1. <span style="FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" > <script type="Text/javascript" >
  2. function Newload () { //New page loaded event
  3. For (var i = 1; I <= 3; i++) {
  4. var anchor = document.getElementById ("anchor" + i); //Find each anchor
  5. Listener (anchor,i); //listener function
  6. }
  7. }
  8. function Listener (anchor, i) {
  9. Anchor.onclick = function () {//Add click event for anchor
  10. Alert ("you clicked Anchor" + i); //Give a click Response
  11. }
  12. }
  13. Window.onload = Newload; //Assign the Newload event to the page load
  14. </script></span>
Run Result: Prompt for corresponding prompt information

Result analysis: The result of the optimization is that we separate the declared variables from the click events. The scope chain explained by the above explanation: page load, first execute listener function, and listener function need anchor variable, in listener function scope chain not, will go to the next level scope chain, that is to find newload in anchor, Because it has been determined in listener which anchor click the corresponding message, so just find the corresponding anchor in Newload, not wait for the loop to produce Anchor4.

because the time to contact JavaScript is short, the understanding of the wrong place is welcome to correct.

1: "Closure in JavaScript is actually a function that is created during the function run, and when the above function is executed, a closure is created, and the closure references the anchor in the Newload scope. "
It should be: When the above function is executed, a closure is created, and the closure references the I in the newload scope.
2: "Result analysis: The result of optimization is that we separate the declared variables from the click events." The scope chain explained by the above explanation: page load, first execute listener function, and listener function need anchor variable, in listener function scope chain not, will go to the next level scope chain, that is to find newload in anchor, Because it has been determined in listener which anchor click the corresponding message, so just find the corresponding anchor in Newload, not wait for the loop to produce Anchor4. "It should be: Listener (anchor,i); function 3 execution results in 3 different closures, referencing different anchor and I respectively. So execute Anchor.onclick = function () {alert ("You clicked Anchor" + i), and a different I variable is found based on the scope chain of 3 different "execution contexts".
3: Summary: The sub-function finds the first-time stored class value based on the closure of the scope chain that has the "execution context object" at the time.
4: Closures are dynamic allocations at execution time and maintain memory of the state at that time.
5: The runtime context is unique for each execution of the function, so multiple calls to the same function result in multiple run-time contexts being created and the execution context is destroyed when the function is executed. Each run-time context is associated with a scope chain.

Scoped chains and closures in JavaScript

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.