JavaScript Advanced (ii) variable scope

Source: Internet
Author: User
Tags variable scope

Local variable Traps

Look at the code first:

    1. function foo () {
    2. var a = "Hello"
    3. b = "World"
    4. return a + B;
    5. }

When this function is finished, it returns HelloWorld, and the result is really no problem. But there's a detail in it. Two local variables one has VAR in front and the other is not. This does not seem to affect execution, but in fact without Var, the variable becomes a global variable. You can call alert outside of this function (b) and you'll know when you try. A baffling global variable sometimes causes a strange bug, so be sure to remember that the local variable declaration must use VAR before

Variable declaration Promotion

Look at the code again:

    1. var foo = "Hello"
    2. function Test () {
    3. Alert (foo);
    4. var foo = "World";
    5. }
    6. Test ()

What is the content of alert when the code executes? The answer is undefined. Intuitively, when running alert, the variable foo is not declared and does not exist. Since the local scope does not, then go to the global scope to find, it should be "hello" is ah. Why is it? This is the variable declaration elevation. The declaration of any variable within a function is promoted to the top of the function, so the test function above is equivalent to

    1. function Test () {
    2. var foo;
    3. Alert (foo);
    4. foo = "World";
    5. }

So it's going to be undefined. Notice here that the promotion is just a declaration, the Code of the assignment is still in place. And the part of the declaration is not related to the execution of the declared code, such as

    1. function Test () {
    2. Alert (foo);
    3. if (false) {
    4. foo = "World";
    5. }
    6. }

Modify the test function to look like this, and the result is still the same. The statement is still in advance, although this line of code will not be run.
This is the variable declaration promotion, let's look at an example

    1. function Test () {
    2. Foo1 ();
    3. Foo2 ();
    4. function foo1 () {alert ("Foo1")}
    5. var Foo2 = function () {alert ("Foo2")}
    6. }

What happens when the test function executes? The result is that foo1 is alert out, then JS error "Undefined is not a function". There's a difference between declaring a function's elevation inside a function. Foo1, a function is declared to define a function, then the Declaration and function body are promoted, but foo2 with a variable way to define the function, is promoted only declaration, the function body is not promoted, so when the execution of Foo2 (), Foo2 is not assigned, is undefined.

It seems that because JS has variable declaration promotion, then you can not use the C language inside the block-level scope, then I really want to use, how to do? One way to do this is to use an anonymous function, for example:

    1. var foo = "Hello"
    2. function Test () {
    3. Alert (foo);
    4. (function () {
    5. var foo = "World";
    6. })()
    7. }
    8. Test ()

When the test function is changed to this, the result of alert is "Hello", and the Foo in the anonymous function cannot be found anywhere else.

Local variables in closures

Before I recruited the front-end, asked the candidate such a topic, said please write a function that can return the sequence of incrementing integers, he gave me the answer is this

    1. var i = 0;
    2. function Increase () {return i++;}

The increment sequence is returned when the function increase is called repeatedly. But I went on to ask if someone had failed to change the I how, he speechless. In fact, the key to this problem is to create a very safe place to put this I, so that the variable can only be accessed by a function, so an optional answer is this. At this point, increase returns the increment sequence. And I put it in a very safe place. Would not have been destroyed.

    1. var increase = (function () {
    2. var i = 0;
    3. return function () {return i++;}
    4. })();

JS closure is a very worthy of talking about the content, easy to use, but there are a lot of pits, below I specifically open an article to say.

Global variables

Countless books that speak high-quality code will refer to global variables, the big kill, programmers are repeatedly warned, unless you have sufficient reasons, otherwise do not use global variables, JS is no exception. However, JS has a special place is not the main method, the entry code must be written, but the code written in this place will inevitably use variables, these variables are global variables, then how to deal with this problem? The answer is still an anonymous function, like this:

    1. (function () {
    2. var a = "a";
    3. var B = "B";
    4. var c = "C";
    5. Foo (A, B, c);
    6. })()

Place the entry code in an anonymous function so that the variables a, B, and C are hidden inside the function, avoiding the appearance of global variables.

JavaScript Advanced (ii) variable scope

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.