JavaScript closures Detailed

Source: Internet
Author: User

Today we explain the closure concept in JavaScript from the memory structure.

Closure: Refers to a function that has access to a variable in another function scope. A common way to create closures is to create another function inside a function.

There is no block-level scope in JavaScript, so we use closures in order to declare to a function some local variables that only the function can use, so that we can greatly reduce the variables in the global scope and purify the global scope.

The benefits of using closures are, of course, a cost, and the cost is the memory footprint.

How to understand the above statement?

The execution of each function creates a function execution environment that is related to the function, or the function execution context. In this execution context there is an attribute scope chain (scope chain pointer), which points to a scope chain structure, and the pointer in the scope chain points to the active object corresponding to each scope. Normally, a function creates the function execution context and the corresponding scope chain when the call is started, releasing the space occupied by the function execution context and the corresponding scope chain at the end of the function execution.

Like what:

    // declaring functions    function Test () {    var str = "Hello world";    Console.log (str);    }     // calling functions    Test ();

The structure is generated in memory when the function is called:

But the closure is a bit special, because the closure function can access the variables in the outer function, so the outer function at the end of execution, the scope of the active object is not released (note that the execution environment and the corresponding scope chain will be destroyed after the completion of the outer function execution), but is referenced by the scope chain of the closure function, The scoped active object of the outer function is not destroyed until the closure function is destroyed. This is why closures are taking up memory.

So the use of closures is good, there are disadvantages, the abuse of closures will result in a large amount of memory consumption.

There are other side effects of using closures, which can be said to be bugs, or not, and there may be different views about different businesses.

This side effect is that the closure function can only take the final value of the outer function variable.

The test code is as follows: (jquery object used here)

 /*   closure defect    ( function   ($) { var  result = new   Array (), I  = 0;  for  (; I<10;i++ = Span style= "color: #0000ff;" >function   () { return   I;    }; }    $.    RES1  = result;    }) (JQuery);  //  Executes the function in the array  $. Res1[0] (); 

The above code first opened a private scope through an anonymous function expression, this anonymous function is what we said above the outer function, the outer function has a parameter $, but also defines the variable result and I, through a for loop to the array result assignment an anonymous function, this anonymous function is the closure , he accesses the variable I of the outer function, in theory the array Result[i] () will return the corresponding array subscript value, but the actual situation is not as good as it wants.

such as the above code $. Res1[0] () was executed with a result of 10.

Why is this, because the final value of I is 10.

Let's explain in detail what happens in memory when the code above executes:

So is there a way to fix this side effect? Of course!

We can use the following code to achieve our expectations.

    /*Fix closure defects*/    (function($){    varresult =NewArray (), I= 0;  for(; i<10;i++) {Result[i]=function(num) {return function(){    returnnum;    }} (i); }    $. RES2=result;    }) (JQuery); //calling the closure functionConsole.log ($. Res2[0] ());

What happened to the above code in memory? We also use one of the following illustrations to explain in detail. Understand the above diagram, we will not be difficult to comprehend the following figure.

As long as we understand the above three graphs, we can understand the principle of the closure in JavaScript, as well as the benefits and drawbacks of closures, in our code reasonable use of closures to achieve the code clean and efficient.

Read the original: JavaScript closures

JavaScript closures Detailed

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.