My understanding of the closure in JS

Source: Internet
Author: User
Tags definition closure function definition functions variables return variable

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

But he is also JS ability to improve the one link can not be bypassed, almost every interview must ask questions, because in answer to the time. The depth of your answer, the understanding of terminology and the description of the operation of JS internal interpreter, can be seen in your JS actual level. Even if you don't get it right, It also allows the examiner to have an assessment of your level. So let me start by saying that I understand the closure of JS.

Closures are a lot of language features, in JS, closures are mainly related to JS several other features: Scope chain, garbage (memory) recovery mechanism, function nesting, and so on.

Before understanding closures. It's best to understand the meaning of the scope chain first, in simple terms, a scope chain is a function created at the time of definition to find an index of the value of the variable being used, and his internal rule is to put the local variable of the function itself at the front, putting the variables in its parent function second, Put the variables in the higher level function back, and so on until the global object. When the function needs to query the value of a variable, JS interpreter will go to the scope of the 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 not continued. If you find the last variable you didn't find, the interpreter will return undefined.

Understand the scope chain, we look at JS memory recovery mechanism, in general, a function at the beginning of execution, it will be defined in the variables of the memory space to save, in preparation for the following statement, wait until the function finished back, These variables are considered useless. The corresponding memory space is also reclaimed. The next time you execute this function, all the variables return to their original state and are assigned a new value. But if another function is nested inside this function, And this function is likely to be called externally. And this intrinsic function uses some variables of the external function. This memory recovery mechanism can cause problems. If the external function returns, the internal function is called directly, Then the intrinsic function cannot read the value of the variable in the external function he needs. So when the JS interpreter encounters a function definition, it automatically saves the function and the variables that he or she might use, including the local variables and the variables (free variables) of the parent and ancestor-level functions. That is, building a closure, These variables will not be reclaimed by the memory collector. The closure is destroyed only when the internal function cannot be invoked (for example, when it is deleted or without a pointer), and no variable that is referenced by the closure is reclaimed by the next memory recycle startup.

That is, with closures, nested function structures can work, which is also consistent with our expectations. Then, closures have some features that often make programmers feel hard 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] (); 3
result[1] ();//3
result[2] ();//3

In this code, the programmer wants the variable i in the Foo function to be used by the internal loop function, and they can get their index separately, but in fact, only the last value of the variable can be obtained, that is to say. The free variable recorded in the closure is only 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 can also be changed.

One of the ways to solve this problem is to have the internal function execute immediately when the loop is created, and capture the current index value and then record it in one of its own local variables. Then, using the return function method, rewrite the internal function so that the next time the call returns the value of the local variable, and the improved code:

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

I'll explain it here. Here are 2 other techniques used to call anonymous functions and return functions immediately. It is also difficult for beginners to understand the part.



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.