JavaScript scopes and scope chains

Source: Internet
Author: User
Tags variable scope subdomain

I. About block-level scopes
When it comes to JavaScript's variable scope, it differs from the Class C language we normally use.
For example, the following code in C #:

    1. static void Main (string[] args)
    2. {
    3. if (true)
    4. {
    5. int num = 10;
    6. }
    7. System.Console.WriteLine (num);
    8. }

If this code is compiled, it cannot be passed because the "name Num does not exist in the current context". Because here
The scope of a variable is defined by curly braces, called a block-level scope.
At the block-level scope, all variables are within the curly braces defined, starting with the definition and closing the curly brace.
Can be used within the range. This range will not be accessible. That means the code

    1. if (true)
    2. {
    3. int num = 10;
    4. System.Console.WriteLine (num);
    5. }

This can be accessed because the variable is defined and used within the same curly brace.
In JavaScript, however, there is no concept of block-level scope in JavaScript.
second, the scope in JavaScript
In JavaScript, the following code:

    1. if (true) {
    2. var num = 10;
    3. }
    4. alert (num);

The result of the run is pop-up 10. So how is the scope of the variable scoped in JavaScript?
2.1 function scoped variable scope
In JavaScript, only functions can limit the scope of a variable. What do you mean?
That is, in JavaScript, variables defined inside a function can be accessed inside a function, but outside of the function
cannot be accessed. Look at the following code:

    1. var func = function () {
    2. var num = 10;
    3. };
    4. try {
    5. alert (num);
    6. } catch (e) {
    7. Alert (e);
    8. }

When this code runs, an exception is thrown, and the variable num is undefined. In other words, a variable defined in a function cannot
Used outside of the function, of course, within the function can be used arbitrarily, even before the assignment. Look at the following code:

    1. var func = function () {
    2. alert (num);
    3. var num = 10;
    4. alert (num);
    5. };
    6. try {
    7. Func ();
    8. } catch (e) {
    9. Alert (e);
    10. }

After this code runs, it will not throw an error, pop the window two times, respectively undefined and 10 (as for why, explained below).
It can be seen from here that variables can be accessed only in functions. Similarly, functions in this function can also be accessed.
2.2 subdomain access to parent domain
As I said earlier, the function can limit the scope of the variable, then the function in the function becomes the subdomain of the scope. In the subdomain
The code in can access variables in the parent domain. Look at the following code:

    1. var func = function () {
    2. var num = 10;
    3. var sub_func = function () {
    4. alert (num);
    5. };
    6. Sub_func ();
    7. };
    8. Func ();

Copy Code

The result of this code execution is 10. You can see the variable access situation as described above. However, accessing the parent domain in the subdomain
The code is also conditional. As in the following code:

    1. var func = function () {
    2. var num = 10;
    3. var sub_func = function () {
    4. var num = 20;
    5. alert (num);
    6. };
    7. Sub_func ();
    8. };
    9. Func ();

This code is more than the previous one "var num = 20;", this code is in the child domain, then the subdomain access to the parent field is sent
Has changed, this code prints the result is 20. That is, num that is accessed by the subdomain at this time is a variable in the subdomain, not in the parent domain.
This shows that there are certain rules to visit. Using variables in JavaScript, the JavaScript interpreter begins with the current
Search in the field for the definition of the variable, if any, the variable is used, and if not, the variable is found in the parent domain.
And so on, until the top-level scope, still not found, throws the exception "variable not defined". Look at the following code:

    1. (function () {
    2.         var num = ten;
    3.         (function () {
    4.                  var num =;
    5.                 (function () {
    6.                          alert (num);
    7.                }) ()
    8.        });
    9. }) ();

This code is executed after printing out 20. If you will "var num = 20;" Remove it, then the print is 10. Again, if you remove
"var num = 10", an undefined error occurs.
third, scope chain
With the partitioning of JavaScript scopes, you can link the access scope of JavaScript to a chain tree-like structure.
Once you have a clear understanding of the scope chain of JavaScript, the variables and closures for JavaScript are very clear.
Use the drawing method below to draw the scope chain.
3.1 Drawing rules:
1) Scope chain is an array of objects
2) All script is a 0-level chain, with each object occupying one position
3) usually see the function to extend a chain out, the first level to expand
4) Access first look at the current function, if not defined up to the top level chain check
5) so reciprocating, until the 0-level chain
3.2 Examples
Look at the following code:

  1. var num = 10;
  2. var func1 = function () {
  3. var num = 20;
  4. var func2 = function () {
  5. var num = 30;
  6. alert (num);
  7. };
  8. Func2 ();
  9. };
  10. var func2 = function () {
  11. var num = 20;
  12. var func3 = function () {
  13. alert (num);
  14. };
  15. Func3 ();
  16. };
  17. Func1 ();
  18. Func2 ();

The following analysis of this code:
First, the entire code is a global scope, can be marked as a 0-level scope chain, so long there is an array
var link_0 = [num, func1, FUNC2]; This is described in pseudo-code
Here func1 and Func2 are functions, so two 1-level scope chains are drawn, respectively,
var link_1 = {func1: [num, Func2]}; This is described in pseudo-code
var link_1 = {func2: [num, func3]}; This is described in pseudo-code
The first Class 1 chain derived from the 2-level chain
var link_2 = {func2: [num]}; This is described in pseudo-code
The second 1-level chain does not define a variable, is an empty chain, is expressed as
var link_2 = {func3: []};
To integrate the above code, you can represent the scope chain as:
This is described in pseudo-code
var link = [//0-level chain
Num
{func1: [//First 1-chain
Num
{FUNC2: [//2-chain
Num
] }
]},
{FUNC2: [//second 1-chain
Num
{func3: []}
]}
];
The image is represented as

Figure: 01_01 scope chain. gif
Note: The chain of the graph with the JS code display, and then highlight the time is very clear.
With this map of the scope chain, you can see very clearly how the access variable works:
When you need to use a variable, you first look for the variable on the current chain, and if you find it, use it directly, not
Look up again, if not found, then go up the first-level scope chain until the 0-level scope chain.
If you can determine very clearly the level of the scope chain to which the variable belongs, then in the parsing JavaScript
The code and the use of advanced JavaScript features such as closures can be very easy (at least I do).
four, variable name promotion and function name promotion
With access rules for scope chains and variables, there is a very tricky problem. Let's look at the following
The JavaScript code:

    1. var num = 10;
    2. var func = function () {
    3. alert (num);
    4. var num = 20;
    5. alert (num);
    6. };
    7. Func ();

What would be the result of the execution? You can think about it, I don't know the answer first.
Let's start by analyzing this piece of code.
This code has a 0-level scope chain with members Num and func. Under Func is a Level 1 effect
The domain chain, which has member Num. Therefore, when the function func is called, it is detected in the current scope
The variable num is defined, so the variable is used. However, NUM is not assigned a value at this time because the generation
The code is running from the top down. So the first time you print is undefined, and the second time you print is 20.
Are you correct?
Code like this is defined later, and the previous usage is common in JavaScript.
Problem. It is as if the variable was defined at the beginning, and the result is like the following code:

    1. var num = 10;
    2. var func = function () {
    3. var num; It feels like it's defined here, but it's not assigned the same value.
    4. alert (num);
    5. var num = 20;
    6. alert (num);
    7. };
    8. Func ();

Then this phenomenon is often referred to as variable name elevation. There are also function names that promote this. As in the following code:

    1. var func = function () {
    2. Alert ("Call the Outside function");
    3. };
    4. var foo = function () {
    5. Func ();
    6. var func = function () {
    7. Alert ("Call the internal function");
    8. };
    9. Func ();
    10. };

Okay, so what's the result of this code? Or there should be something different, I do not say not to leave the reader to think it!
The next article to do the answer.
Because of these differences, it is recommended to write the variables at the beginning of the actual development,
That is, the variable is defined at the beginning of the function, similar to the C language. This in the JS library also
This is done, such as jquery.

v. Summary
Okay, this article is mainly about how the lexical scope of JavaScript is going on, and explaining
How to analyze the scope chain, and the access of variables.

JavaScript scope and scope chain

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.