Javascript notes and summaries (1-5) closures

Source: Internet
Author: User

"Example 1"

<script>function  t1 () {    var = +;     function T2 () {        alert (age);    }     return T2;} var tmp = T1 (); var age = a; tmp (); </script>

Pop up 20

Analysis

function T1 () {    var;    Function T2 () {        alert (age);    }     return T2;}

In most languages, T1 is called to execute, the memory is requested, and its local variables are pushed into the stack, the T1 function executes, and the internal local variables are destroyed as the function exits, causing the local variable of age = 20 to disappear.

Therefore, T1 (); After execution, the local variables within the T1 are freed, as understood by the C language.

function T1 () {
    var  - ;    Function T2 () {        alert (age);    }
return T2;
}

In JS, T1 in the execution of the process, and generated a T2,

And from the scope, T2 can access the Age = 20,

So "age = 20" did not disappear, but was captured by T2,

At the same time, "Age = 20" and the return of the T1 function form a package returned, became a "environment package",

This package belongs to T2, so it is called "closure".

T2 the surrounding environment, that is to say T2 by their own ecological environment,

That is, even if the T1 executes, through T2, the variable can still be accessed: In this case, the function is not an isolated function, even the surrounding variable environment, forming a closed environment package, common return .

In a nutshell: The scope of a function depends on the declaration, not on when it is called .

"Example 2"

1 functionprev () {2     varLeg = "Alexis";3     varArsenal_leg =function(){4         returnleg;5     } 6     returnArsenal_leg;//Arsenal's thigh was Sanchez in the first half of the season.7 }8 9 functionAfter () {//came to the second half of the seasonTen     varLeg = "Giroud"; One     varArsenal_leg = prev ();//Call prev (), Arsenal_leg function came to the second half of the season A alert (Arsenal_leg ()); - } -After ();//who's the thigh ? the  -</script>

Popup: Alexis

"Analysis":

Line:14 execution after ();

Line:12 alert Arsenal_leg ();

Line:11 Aesenal_leg () = prev ();

Line:6 return Arsenal_leg ();

Line:3 function declares return leg; "Really executed function"

line:2 var leg = "Alexis"; "Scopes to look for when a function is declared "

" Example 3" closure counter, multi-person development JS Program, need a global counter

Solution ① Set up a global variable

window.cnt = 0;

Call ++window.cnt

This scheme is feasible, but it pollutes the global variables, and secondly, it may contain window.cnt = * * * In the process of human beings. The counter will be corrupted (so avoid using global variables)

Scenario ② using closures to maintain a variable that other people can't pollute. Do a technology device

<script>function  counter () {    var cnt = 0;     var function () {        return + +cnt    ;    } return Cnter;} var inc = counter () ; Alert (inc); Alert (Inc ()); </script>

Popped 3 times, respectively:

Simplify the procedure above:

<script>var inc = (function  counter () {    var cnt = 0;     return function () {        return + +cnt;    }}) () ; Alert (Inc ()); Alert (Inc ()); </script>

Then revise the above Program (Inc is still a global variable.) Generally avoid global pollution or conflict at work):

Scenario ① Unified on a global object, such as JQuery-

<script>=// analog jquery$.cnt = (function() {    var cnt = 0;     return function Cnter () {        return + +cnt;    }}) (); Alert ($.cnt ()); alert ($.cnt ()); alert ($.cnt ()) ; </script>

Scenario ② everyone uses their own namespaces (in fact, they put their own variables, functions are placed in an object)

<script>var// General name namespace dee.cnt = (function() {    var cnt = 0;     return function Cnter () {        return + +cnt;    }}) (); Alert (dee.cnt ()); alert (dee.cnt ()); alert (dee.cnt ()) ; </script>

"Example 4" Requirements: Click on 4 li, respectively pop 0,1,2,3

<! DOCTYPE html>for  (var i = 0, lis = document.getElementsByTagName ("Li"), len = lis.length; i < Len; i++) {    = (function(i) {        returnfunction() {            alert (i);        }    }) (i);} </script>

"Wrong wording" (Will pop up 4,4,4,4):

<script>for (var i = 0, lis = document.getElementsByTagName ("Li"), len = lis.length; i < Len; i+ +) {    function() {        alert (i);    }} </script>

"Analysis of the wrong wording":

(Respondents Yang Zhiwang):

"The For loop is executed immediately, so when the onclick trigger, the inner function looks for the variable i, it is found in the Ao+scope, not in the AO, and the variable I in scope has become link.length.",

After the closure has been applied,

"At this point, if the inner function is triggered, he will look for the variable i from his AO and scope (outer function's AO and window scope)." You can see that the AO in outer function has been wrapped

Contains I, and for this for loop, there is a pair of n (function () {}) () that should be created to execute. So each inner function has a specific outer function that contains the variable i. Such

You can output 0,1,2,3 smoothly.

Conclusion: We can see that closures are actually caused by scope, so, broadly speaking, all functions are closures. "

The so-called asynchronous functions are functions that include callbacks such as Ajax, event triggering, SetTimeout, setinterval, and so on.

When parsing a document flow, if you encounter JS code, it executes immediately. If an asynchronous function is triggered during this period, it is stored in the queue structure. When the previous code finishes executing, the browser looks at this queue, such as pending execution

function is executed, and no wait is triggered.

So, that I value will be the biggest one. Because the For loop has run out before the async function is executed. "

Reference: What are the solutions to the effect of closure on Js loop add event?

Javascript notes and summaries (1-5) closures

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.