Javascript closures and javascript closures

Source: Internet
Author: User

Javascript closures and javascript closures

Today, we will explain the concept of closure in javascript from the memory structure.

Closure: a function that has the right to access variables in another function scope. A common way to create a closure is to create another function within a function.

There is no block-level scope in javascript. Generally, to declare some local variables that can only be used by a function, we will use the closure, in this way, we can greatly reduce the variables in the global scope and purify the global scope.

The advantages of using a closure are as follows. Of course, this benefit requires a price. The price is the memory usage.

How can we understand the above sentence?

Each function execution creates a function execution environment related to the function, or a function execution context. In this execution context, there is an attribute scope chain (scope chain pointer). This pointer points to a scope chain structure, and all the pointers in the scope chain point to the activity objects corresponding to each scope. Normally, a function creates the execution context and corresponding scope chain when the call starts to execute the function. After the function execution ends, the execution context and the space occupied by the corresponding scope chain are released.

For example:

// Declare the function test () {var str = "hello world"; console. log (str) ;}// call the function test ();

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


However, the closure is a little special. Because the closure function can access the variables in the outer function, after the execution of the outer function, its scope activity object will not be released (note, the execution environment and corresponding scope chain of the outer function will be destroyed after the execution of the rows), but will be referenced by the scope chain of the closure function until the closure function is destroyed, the scope activity object of the outer function will be destroyed. This is exactly why the closure needs to occupy memory.

Therefore, the use of closures has advantages and disadvantages. Misuse of closures will cause a large amount of memory consumption.

The use of closures has other side effects, such as bugs or failures. Different services may have different opinions.

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

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

/* Closure defect */(function ($) {var result = new Array (), I = 0; for (; I <10; I ++) {result [I] = function () {return I ;}}$. RES1 = result;}) (jQuery); // execute the functions in the array $. RES1 [0] ();

The code above first opens up a private scope through an anonymous function expression. This anonymous function is the outer function we mentioned above. This outer function has a parameter $, at the same time, the variables result and I are also defined, and an anonymous function is assigned to the array result through the for loop. This anonymous function is the closure, which accesses the variable I of the outer function, theoretically, the array result [I] () returns the corresponding array tag value, but the actual situation is not as expected.

The execution result of the Code $. RES1 [0] () above is 10.

Why? Because the final value of I is 10.

Next we will explain in detail what happened in the memory during the above code execution:

 


 

Is there any 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); // call the closure function console. log ($. RES2 [0] ();

What happened to the above Code in the memory? We also use the following figure for detailed explanation. After reading the figure above, we can easily understand the figure below.

 


 

As long as we understand the three figures above, we can thoroughly understand the principle of the closure in javascript, as well as the advantages and disadvantages of the closure, and reasonably use the closure in our code, the code is neat and efficient.

Read the original article: javascript closure details

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.