[JavaScript] Closures and scopes

Source: Internet
Author: User

Closures are functions that have access to variables in another function scope. A common way to create closures is to create another function inside one function, for example:

1 functioncreatecomparisonfunction (PropertyName) {2 3     return function(Object1, object2) {4          var value1 = Object1[propertyname]; 5          var value2 = Object2[propertyname]; 6 7         if(Value1 <value2) {8             return-1;9}Else if(Value1 >value2) {Ten             return1; One}Else { A             return0; -         } -     }; the}

In the above function, the two lines of code highlighted are the code in the intrinsic function, which accesses the variable propertyname in the external function. Even if the intrinsic function is returned and is called elsewhere, it can still access the variable propertyname. It is also possible to access this variable because the scope of the intrinsic function contains the scope of Createcomparisonfunction ().

When a function is called for the first time, an execution environment and the corresponding scope chain are created, and the scope chain is assigned to a special internal property ([Scope]). Then, use the values of this, arguments, and other named parameters to initialize the active object of the function. However, in the scope chain, the active object of the outer function is always second, and the outer function of the external functions of the active object is in the third position ... To the global execution environment as the end of the scope chain.

During function execution, to read and write the value of a variable, you need to find the variable in the scope chain. Look at the following example:

1 functionCompare (value1, value2) {2     if(Value1 <value2) {3         return-1;4}Else if(Value1 >value2) {5         return1;6}Else {7         return0;8     }9 }Ten  One varresult = Compare (5, 10);

The above code first defines the compare () function and then calls it in the global scope. When compare () is called for the first time, a live object containing this, arguments, value1, and value2 is created. The variable objects for the global execution environment (including this, result, and compare) are second in the scope chain of the Compare () execution environment.

Each execution environment in the background has an object that represents a variable-the variable object. A variable object for a global environment always exists, whereas a variable object of a local environment such as the Compare () function exists only during the execution of a function. When you create the Compare () function, a scope chain is created that contains the global variable object, which is stored in the internal [Scope] property. When the Compare () function is called, an execution environment is created for the function and then the scope chain of the execution environment is built by copying the objects in the [Scope] property. Thereafter, another active object (used here as a variable object) is created and pushed into the front end of the execution environment scope. For the execution environment of the Compare () function in this example, its scope chain contains two variable objects: The local active object and the global variable object. Obviously, a scope chain is essentially a pointer to a variable object list, which only references but does not actually contain variable objects.

Whenever a variable is accessed in a function, a variable with the corresponding name is searched from the scope chain. In general, when the function is finished, the local active object is destroyed, and only the global scope (the variable object of the global execution environment) is saved in memory. However, closures are different.

  A function defined inside another function adds the active object containing the function (that is, the outer function) to its scope chain. therefore, in the scope chain of the anonymous function defined inside the createcomparisonfunction () function, it will actually contain the active object of the external function createcomparisonfunction ().

After the anonymous function is returned from Createcomparisonfunction (), its scope chain is initialized to the active object and the global variable object that contains the Createcomparisonfunction () function. In this way, the anonymous function can access all the changes defined in Createcomparisonfunction (). More importantly, the createcomparisonfunction () function will not be destroyed after execution, because the scope chain of the anonymous function is still referencing the active object. In other words, when the createcomparisonfunction () function returns, the scope chain of its execution environment is destroyed, but its active objects remain in memory until the anonymous function is destroyed, createcomparisonfunction () Object will be destroyed, for example:

1 //Create a function2 varComparename = createcomparisonfunction ("name");3 4 //calling Functions5 varresult =Comparenames (6     {7Name: "Baka"8     },9     {TenName: "Akuma" One     } A ); -  - //dereference an anonymous function (to free memory) theComparenames =NULL;

First, the comparison function created is saved in the variable comparenames, and by setting Comparenames to null to dismiss the function's reference, it is tantamount to notifying the garbage collector to clear it. As the scope chain of anonymous functions is destroyed, other scopes (in addition to the global scope) can be safely destroyed.

  Because the closure carries the scope of the function that contains it, it consumes more memory than the other functions. Excessive use of closures may result in excessive memory consumption.

Due to this configuration mechanism of the scope chain, it is a noticeable side effect that closures can only get the last value of any variable in the containing function . Don't forget that the closure holds the entire variable object, not a particular variable. The following example can clearly illustrate the problem:

1 functioncreatefunctions () {2     varresult =NewArray ();3 4      for(vari = 0; I < 10; i++) {5Result[i] =function() {6             returni;7         };8     }9 Ten     returnresult; One}

This function returns an array of functions. On the surface, it seems that each function should return its own index value, that is, the function of position 0 returns 0, the function of position 1 returns 1, and so on. But actually, each function returns 10. Because the active objects of the createfunction () function are kept in the scope chain of each function, they refer to the same variable i. When the Createfunction () function returns, the value of the variable i is 10, at which point each function refers to the same variable object that holds the variable i, so the value of I within each function is 10.

[JavaScript] Closures and scopes

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.