JavaScript advanced Knowledge Point--staging scope

Source: Internet
Author: User

The code information comes from http://ejohn.org/apps/learn/.

Self-executing, temporary, function
(function() {   var count = 0

This is a simple self-executing anonymous function.

Make a click Count
Document.addeventlistener ("Click", (functionvar numclicks = 0return function  ++false);

The key code is the self-executing anonymous function, which returns a function that triggers the function by clicking on it, and, depending on the closure scope chain, can access the variable Numclick from which the anonymous function was executed.

Why are the values the same?
 for var d = 0; D < 3; d++ )  setTimeout (function() {    console.log (d);      // 2    // 2    // 2 }, 200);

At 200ms, the anonymous function runs three times, depending on the scope chain, which references D, when the external for has already been looped, and D is 3.

How can I output normally?
 for var d = 0; D < 3; d++) (function(d) {  setTimeout(function() {    console.log (d);
0
1
); }) (d);

The anonymous function referenced here is actually the parameter of the self-executing function, the function executes three times, is independent of each other, and the received parameter is 0,1,2 in turn. This is a typical use of self-executing functions.

Anonymous functions are useful when packaging libraries.
(function() {   varfunction() {     //    };     // })();

When developing a library, we do not affect the global namespace. Using self-executing anonymous functions is a good thing to sit on, making the variables inside the library private, and optionally providing an interface for external variables.

Another way of writing
var mylib = (function() {   function  mylib () {     //     }    //     return  mylib;}) ();

JavaScript advanced Knowledge Point--staging scope

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.