JavaScript closure problem and immediate execution function __ block chain

Source: Internet
Author: User
Tags closure function definition garbage collection types of functions

Today I'm going to talk about the immediate execution function of JavaScript and the closure problem.
First, let's take a look at the immediate execution function:

(function () {...}) () and (function () {...} ()) is a common way for two kinds of JavaScript to execute functions immediately, initially I thought it was a bracket wrapped anonymous function, followed by parentheses to call the function, finally reached the function definition immediately after the purpose of execution, and later found that the reason for parentheses is not so. To understand the immediate execution function, you need to first understand the basic concepts of some functions.

function declarations, function expressions, anonymous functions

function declaration: Functions fnname () {...};
Use the function keyword to declare a function, and then specify a function name, called a function declaration.

Functional expression var fnname = function () {...};
Using the function keyword to declare a function, but not naming the function, and finally assigning an anonymous function to a variable called a function expression, is the most common form of function expression syntax.

anonymous function: function () {};
Declaring a function with the function keyword, but not naming it, is called an anonymous function, an anonymous function is a function expression, and an anonymous function has many functions, giving a variable to create a function, assigning an event to an event handler or creating a closure, and so on.

The difference between a function declaration and a function expression is:

The JavaScript engine, when parsing JavaScript code, will ' function declares l ' (function declaration hoisting) The declaration of functions on the current execution environment (scope), The function expression must wait until the JAVASCIRTP engine executes its line to parse the function expression from the top and the next line.

Second, the function expression can be immediately called with parentheses to call the function, the function declaration can not be called only in the form of FnName (). Here are two examples of the difference between the two.

FnName ();
function FnName () {
    ...
}
Normal, because the ' Ascend ' function declaration, the function call can be fnname () before the function declaration

;
var fnname=function () {
    ...
}
Error, variable fnname has not yet saved a reference to the function, the function call must be after the function expression

After you understand some basic concepts of functions, look back (function () {...}) () and (function () {...} () These two types of functions are immediately executed, initially I thought it was a bracket wrapped anonymous function, and followed by parentheses to call the function immediately, then do not know why the parentheses, then understand that to be called immediately after the function body parentheses, then this function must be a function expression, not a function declaration.

(function (a) {
    console.log (a);   Firebug output 123, using () operator
}) (123);

Closures:
A closure is simply a function nested function, or a function defined within a function, which is a bridge linking the inside of a function to the outside of a function.

Closures can be used in many places. Its maximum usefulness is two, one can read the variables inside the function, and the other is to keep the values of these variables always in memory.

Example 1: Take a look at the following code:

Closure concept: function nesting function
T2 () {
    var b=100;
    function t3 () {
        console.log (b);
    }
    return t3 ();
}
T2 ();

The results of the operation are:

In this code, the variable b declared inside the function t2 is a local variable, why the T3 function can print out the value of the B variable at the time of the call. The reasons are as follows:

In the above code, the function t3 is included within the function T2, when all local variables within T2 are visible to T3. But the reverse is not, T3 internal variables, the T2 is not visible. This is the "chain scoped" structure (chain scope) peculiar to the JavaScript language, where child objects look up the variables of all the parent objects at one level. Therefore, all the variables of the parent object are visible to the child, and the opposite is not true.

This is one of the functions of a closure that can read a variable inside a function.

Example 2: Take a look at the following code:

Function F1 () {
var n=999;
Nadd=function () {n+=1}
function F2 () {
alert (n);
return
F2;
var result=f1 ();
Result ();  999
nadd ();
Result (); 1000

In this piece of code, result is actually the closure F2 function. It runs two times, the first value is 999, and the second value is 1000. This proves that the local variable n in the function F1 is kept in memory and is not automatically purged after the F1 call.

Why is that so? The reason is that F1 is the parent function of F2, and F2 is assigned to a global variable, which causes F2 to always be in memory, and the presence of F2 depends on F1, so F1 is always in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call has ended.

Another notable part of this code is the "Nadd=function () {n+=1}" line, which first nadd not use the var keyword, so nadd is a global variable, not a local variable. Second, the value of Nadd is an anonymous function (anonymous functions), and the anonymous function itself is a closure, so the nadd is equivalent to a setter that can manipulate local variables within the function outside of the function.

To get a deeper understanding of what is said, see the following code snippet:

//This code is wrong because the variable i has never been locked//Conversely, when the loop executes, we do not get a numerical value on the click of I//because this time I do get a real value//So say no matter click on that connection,

The final display is I am link #10 (if there are 10 a elements) var elems = document.getElementsByTagName (' a '); for (var i = 0; i < elems.length i++) {elems[i].addeventlistener (' click ', Function (e) {E.preventdefaul
        T ();
    Alert (' I am link # ' + i);

}, ' false '); }//This is available, because he is in the function expression closure Internal//I value as the index of locked, after the loop execution, although the value of the last I becomes the total number of a elements (for example, 10)//But the Lockedinindex value within the closure is unchanged,

Because he's finished.//So when clicking the connection, the result is correct var elems = document.getElementsByTagName (' a '); for (var i = 0; i < elems.length i++) {(function (Lockedinindex) {elems[i].addeventlistener (' click ', F
            Unction (e) {e.preventdefault ();
        Alert (' I am Link # ' + lockedinindex);

    }, ' false ');

}) (i); }
var elem = document.getelementsbytagname (' div '); If there are 5 div for on the page

(var i = 0; i < elem.length i++) {
    Elem[i].onclick = function () {
        alert (i);//Always 5
    };
}

Above is a very common closure problem, click on any div pop-up value is always 5, because when you trigger the Click event when I value is already 5, you can use the following way to solve:

var elem = document.getelementsbytagname (' div '); If there are 5 div for on the page

(var i = 0; i < elem.length i++) {
    (function (w) {
        Elem[w].onclick = function () {
            A Lert (w); 0,1,2,3,4
        }, in turn
    ) (i);
}

Part of the code reference: Nanyi's Blog

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.