JavaScript closure-scope chain of anonymous functions and functions

Source: Internet
Author: User
Before understanding the closure of JavaScript, we need to know the execution sequence of functions in JavaScript. As we have mentioned earlier, there are multiple methods to define a function. The most common method is the following two methods.

Anonymous Functions

Before understanding the closure of JavaScript, we need to know the execution sequence of functions in JavaScript. As we have mentioned earlier, there are multiple methods to define a function. The most common method is the following two methods.

/* First method of defining a function */function fn1 () {alert ("fn1");}/* Second method of defining a function */var fn2 = function () {alert ("fn2 ");}

The first way to define a function is called a function declaration. A function declared in this way will be loaded into the memory before the function is executed. Therefore, no error will be reported if the function is called before the function is defined or after the function is defined.

The second method of defining a function is called a function expression. The function defined in this way will first create a region in the memory, and then point to this region through a fn2 variable. The function in this region is not named at first, this type of function is called an anonymous function or lambda function. If we call fn2 () before creating a function, the program reports an error.

Function scope chain

In JavaScript, when a function is called, an execution environment is created, and an attribute SCOPE is added for each function. This attribute points to a memory, this memory contains all context variables. After a new function is called in a function, the new function still has a SCOPE to execute the SCOPE of the original function and the newly added SCOPE, thus forming a chain structure, this is the scope chain in JavaScript.

Each function has its own execution environment. When the execution flow enters a function, the function environment is pushed into an environment stack. After the function is executed, the stack pops up its environment and the control is handed back to the original execution environment.

The purpose of the scope chain is to ensure orderly access to all variables and functions that the execution environment has the right to access. The frontend of the scope chain is always the variable object in the environment where the code currently executed is located. The next variable object in the scope chain comes from the inclusion environment, and the next variable object comes from the next inclusion environment, which continues to the global execution environment. The variable object in the global execution environment is always the last object in the scope chain.

What do the above paragraphs mean? We will explain it through specific examples and memory model analysis. Let's take a look at the example below. The example below completes the function of simply switching the color attribute color:

// Define a color attribute var color = "red"; // The display color method var showColor = function () {lele.info (this. color);}/* define a function for color switching */function changeColor () {var anotherColor = "blue"; function swapColor () {var tempColor = anotherColor; anotherColor = color; color = tempColor;} swapColor () ;}// call the color switching function to change the color changeColor (); // call the showColor () method showColor ();

Let's take a look at the above Code. The Code first defines a color variable color, and a method for printing the color showColor (). Then, a function changeColor () is defined to change the color "red" in the global scope to "blue ". Note that swapColor () is another function in this function to implement switching.

Next, we start to execute the changeColor () function. As mentioned above, when js executes a function, it creates an execution environment and adds an attribute SCOPE for each function. This attribute points to a memory, this memory contains all context variables. The memory model should be shown in the following figure when the changeColor () function is executed:

Similarly, swapColor's scope chain points to the global scope at the top. The next level points to the scope of its changeColor function, and finally to its own scope.

Next, the swapColor function is executed. The first code is var tempColor = anotherColor. It first searches for whether the tempColor attribute exists in its own scope. Based on the figure above, we can see that, the tempColor attribute exists in the scope of swapColor, so it changes the value of tempColor from "red" to "blue ".

The second code is anotherColor = color. First, it first searches for the anotherColor attribute in the swapColor scope. If it is not found, it searches for the attribute in the changeColor scope at the upper level through the scope chain, change the anotherColor attribute from blue to red ".

The third code is color = tempColor. The attribute search method is the same. First, search for the attribute in your own scope. If it is not found, search for the attribute in the scope at the upper level. The color attribute is eventually found in the global scope, so it changes the color attribute in the global scope from "red" to "blue ".

Finally, after the swapColor function is executed, the function will be garbage collected, and the changeColor function is also executed and garbage collected. Then we call the showColor () method and create a new execution environment and scope chain for the function.

In the scope chain of showColor, there are two points: the global scope of the top layer and its own scope. When the showColor function is executed, it does not find the color attribute in its own scope, so it searches for it in the global scope at the upper level, at this time, the color attribute in the global scope has been changed to "blue", so the program will eventually print the color "blue ".

The above is the JavaScript closure-the scope chain of anonymous functions and functions. For more information, see the PHP Chinese website (www.php1.cn )!

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.