Talking about the closure in JavaScript

Source: Internet
Author: User
Tags closure

Introduced definition: The closure only has the right to access functions in the scope of another function.

Simply put, when a function A is finished, the closure does not allow the GC (the JavaScript recycling mechanism) to reclaim the resources used by a, since the execution of the internal function B of a requires a dependency on the variables in a.

code example:

Window.onload =function(){        functioncreatecomparisonfunction (PropertyName) {return function(Object1, object2) {varValue1 =Object1[propertyname]; varvalue2 =Object2[propertyname];                Console.log (arguments); if(Value1 <value2) {                    return–1; }Else if(Value1 >value2) {                    return1; }Else{                    return0;        }            }; }        varComparenames = createcomparisonfunction ("name"); varresult = Comparenames ({name: "Nicholas"},{name: "Greg"});

In this example, when you call the play Createcomparisonfunction function, the local active object, that is,

Call Createcomparisonfunction This function is generated by the active object that should be destroyed, but as we call the statement below, Comparenames still succeeds in calling, and notice that we are inside the anonymous function (3 lines) is a reference to the west of the Createcomparisonfunction parameter, in fact, this is a closure of a small embodiment of it.
No, I'll prove it again. No harm: In line fifth of the above code, there is not a control with the output statement, which is printed by the anonymous function of the anonymous parameter arguments, the result is attached:

From this, it is not difficult to see, in the anonymous function of the <function scop>, the preservation of the scope chain, wherein there is createcomparisonfunction form parameter propertyname: "Name".

Closure Considerations 1: Closures and variables:

The variable in the closure has its particularity, but in fact, it is quite common to delve into it:

On the code:

functioncreatefunctions () {varresult =NewArray ();  for(vari = 0; I < 10; i++) {Result[i]=function(){                    returni;            }; }            returnresult; }        varResults =createfunctions ();  for(vari = 0; I < 10; i++) {alert (Results[i] ()); }

Final output: each time the output is ten

Explanation: When the createfunction () function returns, the value of the variable i is 10, at which point each function refers to the same variable object that holds the variable i, so ...

Of course, we can solve this problem in a very ingenious way:

functioncreatefunctions () {varresult =NewArray ();  for(vari = 0; I < 10; i++) {Result[i]=function(num) {//use num to save the initial value of I                    return function(){                        returnnum;            }} (i); }            returnresult; }        varResults =createfunctions ();  for(vari = 0; I < 10; i++) {Console.log (Results[i] ()); //0,1,2,3,4,5,6,7,8,9}

The best way, it is self-evident, perhaps this is the language of the wonderful bar.

After the closure, let's talk about something that is closely related to the scope chain and the active object:

official: When a function is called, an execution environment and the corresponding scope chain are created, then the active object of the function is initialized with the values of the arguments and other command parameters, but in the scope, the active object of the outer function is always the second bit, The active object of an external function's external function is always in the third place, knowing the global execution environment at the end of the scope.

What do you mean: Brother Summary for the following:

1: A function is created, that is, the scope chain is generated.

2: The scope chain is stored in arguments or other parameters (see above in this article).

3: What is acting on the chain:

Introduction Scope: Any programming language has the concept of scope, simply speaking, the scope is the scope of the variable and function, that is, the scope controls the visibility of variables and functions and life cycle. In JavaScript, the scope of a variable has both global scope and local scope.

Scope chain: That is, a collection of scopes. It is essentially a pointer to a variable object list, which references but does not contain variable objects.

On the code: Test1:

varName = "the window"; varnum = 100;//global Variable Object    varObject ={name:"Ny Object",        //The active object starts-------The local active object------------------Getnamefunc:function(num) {return function(){                returnnum;        }; }//end of active object:------------------------------------------------------------------------    }; Console.log (Object.getnamefunc (500) ());// -

Test2:

varName = "the window"; varnum = 100;//global Variable Object    varObject ={name:"Ny Object",        //The active object starts-------The local active object-------------------------------------------------Getnamefunc:function(num) {return function(num) {returnnum;        }; }//end of active object:------------------------------------------------------------------------    }; Console.log (Object.getnamefunc (500) (50)); 50

Test3:

varName = "the window"; varnum = 100;//global Variable Object    varObject ={name:"Ny Object",        //The active object starts-------The local active object-------------------------------------------------Getnamefunc:function(){            return function(){                returnnum;        }; }//end of active object:------------------------------------------------------------------------    };   Console.log (Object.getnamefunc ()); // -

From the test results of the above three code, it is not difficult to see that the local activity object takes precedence, and then the first level of the Internet looks for the target variable (when the function accesses a variable).

Its complete search path (the longest time) is a chain of scopes.

Talking about the closure in JavaScript

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.