In-depth understanding of the lexical scopes and scopes of JavaScript

Source: Internet
Author: User
Tags subdomain
This article mainly introduces the advanced lexical scopes and scope chains of JavaScript. If you need them, please refer to them. Main content:
1. Analyze the meaning of the lexical scope of JavaScript

2. Resolve the scope chain of Variables

3. When the variable name is upgraded

Recently, many of my friends have thought JavaScript is so simple, but I do not know how to use it. So I have prepared some content for you to share.
This series mainly describes the content of the advanced section of JavaScript, including the scope chain, closure, function call mode, prototype, and some object-oriented things. here does not contain the basic syntax of JavaScript, if you need to understand the basics of students can go to the http://net.itcast.cn to download the free video for learning. well, let's talk about it. Let's go to our topic.

1. Block-level scope
When it comes to the scope of JavaScript variables, it is different from the class C language we usually use.
For example, the following code in C:

The Code is as follows:


Static void Main (string [] args)
{
If (true)
{
Int num = 10;
}
System. Console. WriteLine (num );
}

This Code cannot be compiled because "the name num does not exist in the current context ".
The scope of a variable is limited by curly brackets and is called block-level scope.

In the block-level scope, all variables are in the defined curly brackets, starting from the definition to the ending of the curly brackets.
It can be used within the specified range. If the specified range is exceeded, the Code cannot be accessed.

The Code is as follows:


If (true)
{
Int num = 10;
System. Console. WriteLine (num );
}

It can be accessed here, because the variable definition and use are in the Same curly brackets.

But it is different in JavaScript. JavaScript does not have block-level scope.

II. Scope in JavaScript
In JavaScript, the following code:

The Code is as follows:


If (true ){
Var num = 10;
}
Alert (num );

The running result is a pop-up window 10. How can the scope of the variable in JavaScript be limited?

2.1 function-defined variable scope
In JavaScript, only a function can limit the scope of a variable. What does that mean?
That is to say, in JavaScript, variables defined in the function can be accessed in the function, but outside the Function
Unable to access. See the following code:

The Code is as follows:


Var func = function (){
Var num = 10;
};
Try {
Alert (num );
} Catch (e ){
Alert (e );
}

When this code is run, an exception is thrown, and the variable num is not defined. That is, the variable defined in the function cannot be
When used outside the function, you can use it in the function at will, even before assigning a value, read the following code:

The Code is as follows:


Var func = function (){
Alert (num );
Var num = 10;
Alert (num );
};
Try {
Func ();
} Catch (e ){
Alert (e );
}

After this code is run, no error will be thrown. The window is displayed twice, namely undefined and 10 (for the reason, the following explanation ).

From this we can see that variables can only be accessed in functions. Similarly, functions in this function can also be accessed.


2.2 subdomain access to parent domain
As mentioned above, a function can limit the scope of a variable, so the function in the function becomes a subdomain of this scope.
The code in can access the variables in the parent domain. See the following code:

The Code is as follows:


Var func = function (){
Var num = 10;
Var sub_func = function (){
Alert (num );
};
Sub_func ();
};
Func ();

The result of this code execution is 10. You can see the variable access information mentioned above, but access
The Code is also conditional. For example, the following code:

The Code is as follows:


Var func = function (){
Var num = 10;
Var sub_func = function (){
Var num = 20;
Alert (num );
};
Sub_func ();
};
Func ();

This code has a "var num = 20;" more than the previous one. This code is in the subdomain, And the subdomain accesses the parent domain.
The result of this Code is 20. That is, the num accessed by the subdomain is the variable in the subdomain, not the variable in the parent domain.

It can be seen that there are some rules for access. Using variables in JavaScript, The JavaScript interpreter first
Search for the definition of the variable in the domain. If yes, use the variable. If not, search for the variable in the parent domain.
Similarly, an exception "variable undefined" is thrown until the top-level scope is still not found. See the following code:

The Code is as follows:


(Function (){
Var num = 10;
(Function (){
Var num = 20;
(Function (){
Alert (num );
})()
})();
})();

After this code is executed, print 20. If you remove "var num = 20;", print 10. Similarly, if you remove it again
"Var num = 10", then an undefined error will occur.

Iii. Scope chain
With the division of JavaScript scopes, you can link JavaScript access scopes into a chained tree structure.
Once the JavaScript scope chain can be clearly understood, the JavaScript variables and closures are very clear.
The following uses the plotting method to draw the scope chain.

3.1 draw rules:
1) The scope chain is the array of objects.
2) All scripts are 0-level chains, and each object occupies a single position.
3) when you see that a function is extended from a chain, it can be expanded at the first level.
4) First, check the current function.
5) So reciprocating until the 0-level chain

3.2 Example
See the following code:

The Code is as follows:


Var num = 10;
Var func1 = function (){
Var num = 20;
Var func2 = function (){
Var num = 30;
Alert (num );
};
Func2 ();
};
Var func2 = function (){
Var num = 20;
Var func3 = function (){
Alert (num );
};
Func3 ();
};
Func1 ();
Func2 ();

The following code is analyzed:
-> First, the entire code segment is a global scope, which can be marked as a 0-level scope chain, so there will be an array for a long time
Var link_0 = [num, func1, func2]; // Pseudo Code Description
-> Here, both func1 and func2 are functions, so two level 1 Scope chains are introduced, which are
Var link_1 = {func1: [num, func2]}; // Pseudo Code Description
Var link_1 = {func2: [num, func3]}; // Pseudo Code Description
-> Level 1 chain derives Level 2 chain
Var link_2 = {func2: [num]}; // pseudo code description here
-> The second level 1 chain does not have a defined variable. If it is an empty chain, it is expressed
Var link_2 = {func3: []};
-> After the above Code is integrated, the scope chain can be expressed:

The Code is as follows:


// Use pseudocode to describe
Var link = [// level 0 chain
Num,
{Func1: [// The first level 1 chain
Num,
{Func2: [// Level 2 chain
Num
]}
]},
{Func2: [// Second Level 1 chain
Num,
{Func3: []}
]}
];

-> Represented

Figure: 01_01w.domain chain .bmp

Note: The chained graph is displayed in js Code, which is very clear when highlighted.

With the diagram of this scope chain, you can clearly understand how access variables are implemented:
When you need to use a variable, first look for the variable in the current chain. If you find the variable, use it directly.
Search up; if not, search for the upper-level scope chain until the zero-level scope chain.


If you can clearly determine the level of the scope chain to which the variable belongs
Code and the use of closure and other advanced JavaScript features will be very easy (at least I do ).

Iii. variable name escalation and function name escalation

With the access rules of the scope chain and variables, there is a very tricky problem. Let's take a look at the following:
JavaScript code:

The Code is as follows:


Var num = 10;
Var func = function (){
Alert (num );
Var num = 20;
Alert (num );
};
Func ();

What is the execution result? You can think about it. I will not reveal the answer first.

Analyze this code first.
In this Code, there is a level-0 scope chain, which contains the num and func members. It plays a level-1 Role Under func.
The domain chain contains the member num. Therefore, when the function func is called, it will be detected in the current scope.
The variable num is defined, so this variable is used. However, num is not assigned a value because
The code is run from top to bottom. Therefore, the first print is undefined, and the second print is 20.
Are you correct?

Code is defined later in this way, while the previous usage is also common in JavaScript.
The problem is that the variable is defined at the beginning, and the result is like the following code:

The Code is as follows:


Var num = 10;
Var func = function (){
Var num; // it seems that it has been defined here, but it is not assigned the same value.
Alert (num );
Var num = 20;
Alert (num );
};
Func ();

This phenomenon is often called variable name escalation. function name escalation also exists, as shown in the following code:

The Code is as follows:


Var func = function (){
Alert ("calling external functions ");
};
Var foo = function (){
Func ();

Var func = function (){
Alert ("calling internal functions ");
};

Func ();
};

Okay. What is the result of this code? Or something should be different. Let me leave it alone without thinking about it!
I will answer the question in the next article.

Because of these differences, we recommend that you write the variables at the beginning during actual development,
That is, the variable is defined at the beginning of the function, similar to the C language. This is also in the js library.
This is done, such as jQuery.

Iv. Summary

Well, this article mainly describes how the lexical scope of JavaScript works and its explanation.
How can I analyze the scope chain and variable access? Let's end with another exercise !!!

See the following code execution result:

The Code is as follows:


If (! "A" in window ){
Var a = "defining variables ";
}
Alert ();

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.