"Ascension" of function scope in JavaScript function

Source: Internet
Author: User
Variable elevation of function scope in JavaScript


When we declare a variable within a function with the keyword VAR, the scope of this variable is limited to the current function.

Ascension: Within a scope, regardless of where a variable is declared with Var, the variable belongs to the current entire scope and can be accessed anywhere in the current scope. In JavaScript, this behavior/phenomenon is called "Ascension", where a variable is declared at any place in a scope with Var, and the JavaScript engine "moves" the variable declared with Var to the beginning of the current scope.

Speaking of JavaScript This "ascension" phenomenon, had to think of college time to learn C language, the old C compiler, C language, variables can only be declared at the beginning of the function and definition, in the function to use the variable must be declared at the beginning of the definition, The declaration definition cannot have any other statements that are not declared defined before. Since the C + + language has broken this limit, the new compiler does not have this hard limit.

Relying on JavaScript as a "variable elevation" mechanism is not a good idea. "Function Promotion" we generally use more.

Therefore, "function ascension" is safe to use, when the use of variables in a scope where the variable is in the declaration of the variable, and the "Variable Ascension" phenomenon, we had better not use.

Elevation Symptom code Example:

var a = 2;
Foo ();
function foo () {
    a = 3;
    Console.log (a);
    var A;
}

Console.log (a);

Results:


 


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.