"Ascension" of function scopes in JavaScript

Source: Internet
Author: User

variable elevation of function scope in JavaScript


When we declare a variable with the keyword var inside the function, the scope of the variable is limited to the current function.

Elevation: 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 with Var at any location in a scope, and theJavaScript engine "moves" the variable declared with Var to the beginning of the current scope.

When it comes to the "ascension" of JavaScript , I have to think of the time when I studied C in college, the old C language compiler, the C language, variables can only be declared and defined at the beginning of the function, the variables to be used in the function must be declared at the beginning of the definition , the declaration definition cannot have any other non-declaration-defined statements before it. Since the C + + language has broken this limit, the C new compiler does not have this hard limit.

It is not a good idea to rely on JavaScript as a "variable boost" mechanism. "Function Promotion" we generally use more.

Therefore, "function promotion" is safe to use, when the use of variables within a scope is located in the declaration of variables before the ground, and the resulting "variable promotion" phenomenon, we'd better not use.

Example of elevation phenomenon code:

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

Results:


 


Copyright NOTICE: This article for Bo Master original article, without BO Master permission cannot reprint [http://blog.csdn.net/doctor_who2004].

Elevation of function scope in JavaScript

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.