JavaScript Series 2--Closure detailed

Source: Internet
Author: User

Forwarding please indicate the source: http://www.cnblogs.com/johnhou/p/javascript.html Please respect the author's labor results--john Hou

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 :( the jquery object is used here )

/* Closures defects * /

(function ($) {

var result = new Array (),

i = 0;

for (; i<10;i++) {

Result[i] = function () {

return i;

};

}

$. RES1 = result;

}) (JQuery);

executing functions in an array

$. Res1[0] ();

The above code first opened a private scope through an anonymous function expression, the anonymous function is the outer function we said above, the outer function has a parameter $, and also defines the variable result and I, through The For loop assigns an anonymous function to the array result, the anonymous function is the closure, and he accesses the variable I of the outer function , in theory the array result[i] () returns the corresponding array subscript value. 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 ten.

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 ($) {

var result = new Array (),

i = 0;

for (; i<10;i++) {

Result[i] = function (num) {

return function () {

return num;

}

} (i);

}

$. RES2 = result;

}) (JQuery);

Calling the closure function

Console.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.

The following is my public number, technical Daniel Assembly number, welcome your attention!

JavaScript Series 2--Closure 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.