Block-level scopes for "Javascript" closures __java

Source: Internet
Author: User

In JS we should try to avoid the use of global variables and global functions to prevent naming conflicts, then how to avoid it. JS has a concept of closure, now we use the closure of the block-level scope to explain, this is the closure of the most important concept.

JS itself is not supported like C/c#/java ... In such a language there is a block-level scope, that is, a variable defined in a syntax block that is inaccessible outside of the syntax block.

So, JS how to simulate a block-level scope like C. Let's look at a chestnut first:

For example:

Test ();
 function test () {
    () function () {for
        (var i=0;i<3;i++) {
            console.log (i);//This time I will be in the * * anonymous function in * * * * * * * * * Invalid anonymous function, I was destroyed outside the anonymous function
        }
    }) ();   
    Console.log (i);//output: undefined
}

Creating an anonymous function inside a function is equivalent to creating a private scope within a function, which is good for projects that are developed in larger/multiple people so that each programmer can use his or her own variables in their own functional functions without confusion or conflict.

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.