Talking about the closure of JavaScript

Source: Internet
Author: User
Tags function definition variable scope

JavaScript is a dynamic, weak type of scripting language. Like most programming languages, JavaScript also uses lexical scopes. That is, the execution of a function depends on the scope of the variable. This scope is determined at the time of the function definition, not the function call. function objects can be associated with each other through the scope chain, and variables accessible by the function body can be stored inside the function scope. Closures, an image of the explanation is that the function variables are hidden in the scope chain, so it appears that the function of the variable wrapped up.

To understand closures, you need to distinguish between the following concepts: 1. Scope (scope), 2. Scope chain (scope chain), 3. Run-time context, or the execution environment (execution context); 4. Active object (activation Object) and 5. Global objects, which explain these concepts separately.

1. Scope. In short, the scope of a variable refers to the scope of the variable, or the life cycle of the variable. The variables in JavaScript can be divided into global variables and local variables. Among the global variables are: 1. Top-level functions (that is, functions that are not nested into other functions), variables defined outside the top-level function (also including top-level code snippets outside the top-level loop body), 2. Initialization variables that are not declared by Var, such as the properties of the A=6;3.window object , whereas a local variable is a variable defined inside a function body.

One concept that needs to be differentiated here is the block-level scope and the function scope. Children's shoes with advanced program design development such as Java or C # know that in this type of language, the scope of a variable is strictly restricted to blocks of code, such as the loop body, the IF statement, and so on.

for (int i=0;i<10;i++) {}console.write (i);//error, because the scope of the variable i is limited to the for loop body

JavaScript differs in that its variable scope is the function scope. That is, variables are defined in the body of the function in which they are declared and in any function within which the function is nested. To give an example,

  

function test () {            if (true)            {                var j=0;            }            for (Var k=0;k<10;k++)            {            }            console.log (k);            Console.log (n);            Console.log (j);            var n=3;        }        Test ();

Which k=10,n=undefined,j=0.

2. Scope Chains and global objects

A scope chain, in short, is a sequence of all objects, functions, and variables that can be accessed when the function executes. When the function is executed, the variables are parsed in the order in which they are arranged. If this variable is not resolved on this chain, then the program throws an exception.

The following three scenarios analyze the scope chain: 1. In the topmost code of JavaScript (that is, code that is not included in any function definition), the scope chain consists of a global object; 2. In the body without nested functions, there are two objects on the scope chain, the first is the object that defines the function arguments and local variables, and the second is the global object. Within a nested function body, there are at least three objects on the scope chain.

When a function is created, its scope chain fills in the global object, and the global object contains all the global variables. For example, the following function:

  

function A (x, y    ) {var b=x+y;     return b;  }

When the SUM function is created, its function scope is as follows:

3. Execution environment and Activity objects

When function a executes, an execution environment is generated, or the run-time context is called (execution contexts). An active object is a new object that consists of values that are copied into the run-time context, in the order in which they appear in the function. It contains the function's local variables, named parameters, the Parameters collection, and this. It is pushed into the forefront of the scope chain, and as the first object, the active object is destroyed when the run-time context is destroyed. If this function is nested within other functions, then the second object of the runtime context is the containing environment, and the third object is the containing environment of the environment, one analogy, and finally the global object. The run-time context refers to all of these object sets.

  

When the function executes, the order of the parsed variables is parsed according to the order of the object, and if the corresponding variable is encountered in the object, then the parsing stops. These objects arrange the data structure like chains, so the image is called the scope chain.

When we understand these definitions, it's easier to get back to the closure.

First look at a piece of code:

function Checkscope () {  var scope= ' local scope ';   function f ()   {      return  scope;   }       return F;}     var result=Checkscope () (); Console.log (result);

Here by the way, we usually write code when we must form a good habit, especially to pay attention to the problem of indentation, good indentation can not only make the program more beautiful, but also more easy to read, not easy to go wrong.

The result of the above code output is the local scope. A lot of people will be puzzled, they think that since scope is a local variable defined within the function checkscope, it should be destroyed when the function returns, thus giving an error.

In fact, this is easy to understand, let's review the concepts mentioned above, we describe the scope chain as an object list, which contains the data that all functions can access. Each time a JavaScript function is called, a new object is created to hold the local variable and the object is added to the scope chain. When the function returns, the object of the bound variable is removed from the scope chain. If there is no nested function (the object is also included in the scope chain of the nested function, that is, the nested function can access the data in the object), and no other application points to the binding object, it is recycled as garbage. But if the function defines a nested function and returns it as a return value or stores it in a property somewhere, an external reference to the nested function will not be garbage collected, and the variable bound object it points to will not be garbage collected.

The Checkscope function returns the scope variable of the scope chain of its nested function f,f that contains the Checkscope function, and when Checkscope returns, F is not garbage collected, so the local variable of scope is saved.

So the most important thing about closures is that you can read the variables within the function and keep the values of those variables in memory.

About the concept of closures about the introduction of these, to recommend a JavaScript learning books, JavaScript authoritative guide, the content is very rich and comprehensive, but also rich in academic atmosphere ~ ~

If you like this article, it would be troublesome to recommend it ~ ~

Talking about the closure of 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.