Some pits for JS variable promotion

Source: Internet
Author: User

1 function log (str) {2    // This method is called for all printing in this article 3    Console.log (str); 4 }

function declarations and variable declarations are always silently "lifted" by the interpreter to the topmost part of the method body

Variable declaration, naming, elevation


In JS, there are 4 basic ways to enter the scope of a variable:

    • Language built-in: All scopes have this and arguments; (Note that arguments is not visible in the global scope)
    • Formal parameters: The formal parameters of the function as part of the function body scope;
    • function declaration: As in this form: function foo () {};
    • Variable declaration: like this: Var foo;

Variable Promotion

function test1 () {      = 5;      Log (a);       Log (WINDOW.A);        var a = ten;      Log (a);     }    Test1 ();

The output is 5, undefined, and in turn, because at parse time is equivalent to

1 var A; 2 a=5; 3 log (a); 4 log (WINDOW.A); 5 a=10; 6 log (a);

Then look at another example:

1 functiontest2 () {2    varA = 1;3    varb = 2;4    varc = 3;5 }6 /*The statement in the test2 is executed so that the variable is raised at this time.7     
8 function Test2 () {9 var a,b,c; Ten var a = 1; One var b = 2; A var c = 3; - } - */

Only function-level scopes, if statements will not have: Test3 ():

function Test3 () {
var a = 1;
Log (a); 1
if (true) {
var a = 2;
Log (a); 2
}
Log (a); 2
}

Promotion of functions


When we write JS, there are usually two kinds of wording:

    • function expression var fn=function fn () {}
    • function declaration mode functions fn () {}

It is important to note that only the function declaration form can be promoted.
The variable assignment was not promoted, but the declaration was promoted. However, the function declaration is a little different, and the function body will be promoted together.

1 functiontest3 () {2 fn ();3    functionfn () {4Log ("I'm from FN");5    }6  }7 test3 ();8  functiontest4 () {9FN ();//FN is not a functionTen    varfn =functionfn () { OneAlert ("I'm from FN test4"); A    } -  } -  test4 ();

function expressions need to be aware of

    • Within function, FN is exactly equal to FN1
    • Outside of function, FN1 is not defined
1 functionTest5 () {2       varfn =functionfn1 () {3Log (fn = = = FN1);//true4Log (fn = = fn1);//true5       }6 fn ();7Log (fn = = = FN1);//fn1 is not defined8Log (fn = = fn1);//fn1 is not defined9     }TenTest5 ();

! compatible
b ();
var a = function B () {alert (' This is B ')};
You can do B under ie. Indicates that different browsers differ in the handling of function expression details.

Add a little function expression

Defines whether the specified function name inside is promoted.

1 functionText7 () {2A ();//TypeError "A is not a function"3 b ();4C ();//TypeError "C is not a function"5D ();//Referenceerror "D is not defined"6 7   varA =function() {};//a points to anonymous functions8   functionB () {};//function Declaration9   varc =functionD () {};//named functions, only c is promoted, and D is not promoted. Ten  One a (); - b (); - c (); theD ();//Referenceerror "D is not defined" - } -Text7 ();

Let's look at the following section of code TEST6, think about what will print?

1 functionText6 () {2    varA = 1;3    functionB () {4A = 10;5       return;6       functionA () {}7     }8 b ();9Log (a);//? Ten } OneText6 ();

||

||

||

|| The output is below

||

||

||

||

||

||

What? What the heck? Why is it 1?
It is important to note that in function B (),
var = a//type of function
a=10; Re-copy 10 to A, where a is the internal variable in function B ()
Return
function A () {}//will not be executed

So, the outside output of a is still the first defined global variable

The declaration of a function is a higher priority than the declaration of a variable

1 functionText6 () {2   functionA () {}3   varA;4Log (a);//print out the function body of a5 6   varb;7   functionB () {}8Log (b);//print out the function body of B9 Ten   //! Note that once the variable is assigned, the variable will be output One   varc = 12 A   functionC () {} -Log (c);// A -    the   functiond () {} -   varD = 12 -Log (d);// A - } +Text6 ();

Order of variable resolution


In general, according to the first four ways to explain

    • Language built-in:
    • Formal parameters:
    • function declaration:
    • Variable declaration:

There are also exceptions:

    • The built-in name arguments behaves strangely, and should appear to be declared after the formal parameter, but before the declaration. This means that if there is arguments in the parameter, it will be higher than the built-in priority. So try not to use arguments in formal parameters;
    • Defining the This variable anywhere will be a syntax error
    • If more than one form parameter has the same name, the last one has a high priority, that is, when it is actually running, its value is undefined;

Cao! So many pits, after the swelling? Write code?


Define variables with Var. For a name, there is always only one var declaration in a scope. This will not encounter scope and variable elevation issues.

ECMAScript reference documents for scope and variable promotion sections:
If a variable is declared in a function body class, it is a function scope. Otherwise, it is the global scope (as a property of global). The variable will be created when execution enters the scope. A block (such as if () {}) does not define a new scope, only the function declaration and the global nature of the code (a single JS file) will create a new scope. Variables are initialized to undefined when they are created. If a variable declaration statement has an assignment operation, the assignment will occur only when it is executed, not when it is created.

Finally, due to the time rush, the demo has a lot of shortcomings, more understanding.

Some pits for JS variable promotion

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.