"Upgrade" of function scope in javascript, javascript

Source: Internet
Author: User

"Upgrade" of function scope in javascript, javascript
Variable upgrade of function scope in javascript


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

Promotion: within a scope, no matter 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 "elevation", that is, a variable is declared With var at any position in a scope, the javascript engine will "move" these variables declared with var to the beginning of the current scope.

When talking about the "Upgrade" of javascript, I had to think that when I was studying C language in the college age, in the old C language compiler, variables in C language can only be declared and defined at the beginning of the function, variables used in a function must be declared at the beginning. No other non-declarative statements must be included before the Declaration definition. Since the c ++ language has broken this restriction, the new c compiler has no such hard limitation.

It is not a good idea to rely on the "variable escalation" mechanism such as javascript. "Function upgrade" is generally used in many cases.

Therefore, "function upgrade" can be safely used. When the place where variables are used in a scope is located before the place where variables are declared, we recommend that you do not use the "variable upgrade" phenomenon.

DEMO code for symptom escalation:

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

Result:


 


Copyright Disclaimer: This article is an original article by the blogger. It cannot be reproduced at [http://blog.csdn.net/doctor_who2004.pdf] without the permission of the blogger.

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.