Closures and scope chains ("JavaScript advanced Programming" reading notes)

Source: Internet
Author: User

When a function is called, an execution environment and the corresponding scope chain are created.

The execution Environment (execution context) defines the other data that variables or functions have access to, and determines their respective behavior. Each function has its own execution environment. When the execution flow enters a function, the environment of the function is pushed into an environment stack. After the function executes, the stack pops up its environment and returns control to the previous execution environment. When code executes in an environment, a scope chain of variable objects is created (scope chain). The purpose of a scope chain is to ensure an orderly access to all variables and functions that the execution environment has access to. A scope chain is essentially a list of pointers to variable objects that reference but do not actually contain variable objects.

Each environment can search up the scope chain to query for variables and function names, but any environment cannot enter another execution environment by searching down the scope chain. But there are other ways to extend the scope chain. Some statements can temporarily add a variable object to the front of the scope chain, and the variable object is removed after the code executes. When the flow of execution enters the following two statements, the scope chain is extended:

    • Catch block for Try-catch statements
    • With statement

Both statements add a variable object to the front of the scope chain. For the WITH statement, the specified object is added to the scope chain. For a catch statement, a new variable object is created that contains the declaration of the thrown error object.

In IE8 and previous versions of JavaScript implementations, there is a standard inconsistency where the error object caught in a catch statement is added to the variable object of the execution environment, not the variable object of the catch statement. In other words, the Error object can be accessed even outside the catch block. IE9 fixed the problem.

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.

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, because a function defined inside another function adds the active object containing the function (that is, an external function) to its scope chain, referring to the following code:

functioncreatecomparisonfunction (PropertyName) {return function(Object1, object2) { var value1 = Object1[propertyname];  var value2 = Object2[propertyname]; if(Value1 <value2) {            return-1; } Else if(Value1 >value2) {            return1; } Else {            return0; }    };}

When the following code executes, contains the scope chain of the function and the inner anonymous function:

var compare = Createcomparisonfunction ("name"); var result = Compare ({name: "Nicholas"}, {name: "Greg"});

When the createcomparisonfunction () function finishes executing, its active object is not destroyed, because the scope chain of the anonymous function is still referencing the active object. The active object of createcomparisonfunction () will not be destroyed until the anonymous function is destroyed:

null;  // dereference an anonymous function (to free memory)

Because the closure carries the scope of the function that contains it, it consumes more memory than the other functions. Excessive use of closures can lead to excessive memory consumption, so consider using closures when absolutely necessary.

  

This configuration mechanism of the scope chain leads to a noticeable side effect, that is, the closure can only get the last value of any variable in the containing function. Because the closure holds the entire variable object, not a particular variable:

function createfunctions () {    varnew  Array ();      for (var i=0; i <; i++) {        function() {            return  i;        } ;    }     return result;}

This function returns an array of functions, and each function returns 10.

The use of this object in closures can also cause some problems. We know that the this object is bound at run time based on the execution environment of the function, and the execution environment of the anonymous function is global, so its this object usually points to the window (this will point to other objects if the function execution environment is changed by call () or apply (). Look at the following example:

var name = "the window"; var object = {    "My object",    function() {        return function () {            returnthis. name;        };     // "The Window" (in non-strict mode)

By saving the This object in an external scope to a variable that the closure can access, you can have the closure access the object, as shown here:

var name = "the window"; var object = {    "My object",    function() {        var  This ;         return function () {            return  that.name;        };     // "My Object"

This and arguments also have the same problem. If you want to access the arguments object in the scope, you must save a reference to the object to a variable that the other closure can access.

Closures and scope chains ("JavaScript advanced Programming" reading notes)

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.