JavaScript Scopes (Consolidation)

Source: Internet
Author: User
Tags variable scope

Several concepts of scope:

1. The functions in JavaScript run in the scope they are defined in, not in the scope in which they are executed.

2, global variables have global scope, the variables declared within the function are defined only within the function body, the scope is local.

3, in the function body, the local variable priority is higher than the global variable.

4, the definition of global variables can not need to declare Var, the definition of local variables must be declared with Var. (usually the recommendation is declared with Var)

The scope is easy to encounter several misunderstandings:

1: Global variable and local variable scope confusion. (Novice misunderstanding)

Fig. 1 Fig. 2

1 and 2, when local variables and global variables are repeated, local variables take precedence over global variables, and the Checkscope () method in Figure 1 re-declares scope with VAR, thus changing and returning a declared local variable scope. There is no re-declaration in Figure 2, so the global variable scope is changed and returned in the Checkscope () method.

2: Ignore the role of variable promotion.

Figure 3

3, the first output is not the ideal "global", but is undefined; this is because local variables are always defined in the function body in JavaScript, and variable declarations in the function body are promoted to the top of the function by default, i.e. Checkscope () The actual order of execution in the method is:

function Checkscope () {

var scope;

Console.log (scope);

Scope = "local";

Console.log (scope);

}

3: Declare global variables with VAR and declare global variables without using var.

JavaScript Scopes (Consolidation)

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.