JS Closed Package Understanding _ Pick

Source: Internet
Author: User

Original Address 1:http://www.cnblogs.com/mzwr1982/archive/2012/05/20/2509295.html

Closures are a relatively abstract concept, especially for JS novices. The explanation in the book is rather obscure, and it is the same for me.

But he is also the ability to improve the JS can not be bypassed, almost every interview must ask questions, because in the answer. The depth of your answer, the understanding of terminology and the description of how the JS internal interpreter works can be seen in the actual level of your JS. Even if you don't answer correctly, You can also have an assessment of your level by the examiner. So let me say my understanding of the closure in JS.

Closures are the characteristics of many languages, in JS, closures are mainly related to JS a few other features: scope chain, garbage (memory) recycling mechanism, function nesting , and so on.

before understanding closures. It's better to understand the meaning of , simply, A scope chain is a function that is created at the time of definition to find an index of the value of the variable used, and his internal rule is to put the local variables of the function itself first, put the variables in its parent function next, and put the variables in the higher-level function later, And so on until the global object. When the function needs to query the value of a variable, the JS interpreter will go to the scope chain to find, from the first local variables to find, if not found the corresponding variable, then to the next level of the chain to find, once the variable is found, it will no longer continue. If you find the last variable , the interpreter returns undefined.

Understand the scope chain, we look at JS memory recovery mechanism , in general, A function at the beginning of the execution, the variables defined in the memory space to save, in case of the subsequent statements to use, wait until the function has been executed to return, these variables are considered useless. The corresponding memory space is also recycled. The next time you execute this function, all the variables go back to their original state. Re-assign the value to use. But if the function is nested inside another function , and . and . This memory-recycling mechanism can cause problems. If the intrinsic function is called directly after the external function returns, the intrinsic function cannot read the value of the variable in the external function that he needs . So the JS interpreter will automatically package, these variables will not be recycled by the memory collector, only if the internal function cannot be called later ( For example, if it is deleted, or if there is no pointer), the closure will be destroyed, and will be recycled when the next memory recycle starts.

In other words, with closures, nested function structures work , which is what we expect. Then, closures have some features that are often difficult for programmers to understand.

Take a look at the following section of code.

var result=[];function foo () {    var i= 0;    for (; i<3;i=i+1) {        result[i]=function () {            alert (i)        }    }};foo (); result[0] ();//3result[1] ();// 3RESULT[2] (); 3

In this code, the programmer wants the variable i in the Foo function to be used by the inner loop function, and can get their index separately, and in fact, only the value that the variable is last reserved, that is. The free variable that is recorded in the closure is just a reference to the variable, not the value of the variable , when the variable is changed, the value of the variable obtained in the closure will also be changed.

One way to do this is to have the inner function execute as soon as the loop is created, capture the current index value, and then record it in one of its own local variables. Then, using the return function method, rewrite the intrinsic function, let the next call , return the value of the local variable, the improved code:

var result=[];function foo () {    var i= 0;    for (; i<3;i=i+1) {        result[i]= (function (j) {            return function () {                alert (j);            };        }) (i);}    ; Foo (); result[0] (); 0RESULT[1] (); 1RESULT[2] (); 2

I'll explain here again. Here are 2 additional techniques that are called immediately by anonymous functions and return functions. It is also a difficult part for beginners to understand.

JS Closed Package Understanding _ Pick

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.