JavaScript-variable and scope chain, javascript-Variable

Source: Internet
Author: User

JavaScript-variable and scope chain, javascript-Variable

JQuery snippet:

 

1 var

2 // Will speed up references to window, and allows munging its name.

3 window = this,

4 // Will speed up references to undefined, and allows munging its name.

5 undefined,

6 // Map over jQuery in case of overwrite

7 _ jQuery = window. jQuery,

8 // Map over the $ in case of overwrite

9 _ $ = window. $,

10

11 jQuery = window. jQuery = window. $ = function (selector, context ){

12 // The jQuery object is actually just the init constructor 'enabled'

13 return new jQuery. fn. init (selector, context );

14 },

15

16 // A simple way to check for HTML strings or ID strings

17 // (both of which we optimize)

18 quickExpr =/^ [^ <] * (<(. | \ s) +>) [^>] * $ | ^ # ([\ w-] +) $ /,

19 // Is it a simple selector

20 isSimple =/^. [^: # \ [\.,] * $ /;

 

Starting from this section, we have stripped jQuery's coat to see what is hidden in it. As mentioned in the previous section, if you look at the anonymous functions of the outer layer without looking at the implementation in it, this implementation is definitely not a closure. However, if jQuery is added, this is definitely a closure application. To understand the closure application, we must first understand its basis. In this section, we encounter fragments that are the basis of variables. (Although this clip contains many knowledge points, please let me talk about it one by one .)

Declare Variables

The English name of the variable is variable. the first three letters of the variable are the Keyword -- var that we declare in JS. So let's first look at how to declare a variable:

 

1 /*

2 * declare the variable format

3 * List of variable expressions initialized by var variable name (optional)

4 */

5 var a = 1, B, c = "test", d = a + B; // although B has not been initialized, the statement is legal

6 alert (a); // "1"

7 alert (B); // "undefined"

8 alert (c); // "test"

9 alert (d); // "NaN"

10 alert (e); // here the compilation error will be thrown: "e" undefined

11 // Similarly, if undefined variables are used during initialization, a compilation error is also thrown.

 

As shown in the preceding example, to declare a variable, you must use the var keyword, followed by a space followed by the variable name. When declaring a variable, we can also help initialize the variable. The initialization value can be any type of value or expression. However, if you try to use an undefined variable name for initialization, The JS compiler will determine that a compilation error occurs, and prevent the program from continuing to run. Whether or not you initialize the declared variables, you can continue to declare the second variable without using the var keyword. All you need is the operator ",". (The operators will be discussed in detail later .) But when you do not initialize declared variables, the variable will be assigned the value "undefined" -- undefined is also an inherent type of JS. PS: The operators used in JS must be English characters or even spaces.

Repeated declared variables ?!

When we declare a variable and declare it again in the subsequent code, what will happen? This may cause repeated definition errors in many other languages, but it is completely legal in JS. In addition, because JS is a weak data type, the variable can be assigned a value of any type. See the following example:

 

1 var a = 1;

2 alert (typeof a); // "number"

3 var;

4 alert (typeof a); // "number"

5 var a = "1 ";

6 alert (typeof a); // "string"

7 a = new String ("1 ");

8 alert (typeof a); // "object"

 

After reading the above example, you may have two questions:

A) Why is the second a or number?

B) Why is object 4?

To answer the first question, we must first understand how a variable is declared. For the second question, we will discuss it in the next section.

How to declare var Variables

When we declare a variable using the var keyword, The JS interpreter performs the following operations:

1) pre-compile the var Keywords of all non-functional blocks in the javascript code block;

2) generate a variable name identifier and allocate space in its scope;

3) run the code to the row where the first var keyword is located;

4) calculate the value of the initialization expression in the order of variable declaration list expressions;

5) each time an initialization expression is calculated, the calculation result is assigned to the corresponding declared variable;

6) continue to run the subsequent code to the next var keyword;

7) Repeat steps 4-7 to the end of the code block;

8) continue to compile and run the next code block.

PS: JS runs a piece of JS code in the unit of a code block, that is, a script tag.

It is precisely because of the way var works. In fact, during program execution, the interpreter cannot see the var keyword at all. He only executes the value assignment statement of the initialization expression. Therefore, the answer to question a is the third sentence in the example. In fact, nothing is done. Therefore, you do not need to worry about repeated variable names in the code. What you really need to worry about is whether the variable value generated by the initialization statement changes as expected. Do not use reserved words as variable names. This is a standard that must be followed in almost all languages.

In addition, the procedure for declaring variables in the function block is similar, but they are created only when the function is run.

No var variable declaration ?!

Many of our friends should have this experience-"We don't need to use var to declare variables and assign values directly !". This is because when the JS interpreter encounters a value expression, it will first find whether the variable has been declared in the scope chain. If this variable is not declared, it is implicitly forced to declare it in the Global scope and assign the value of the expression to this variable.

But why? In fact, everything is derived from the acquisition rules of variables and the combination of the scope chain plus the catalytic effect of the value assignment operator.

Scope chain

Each running context has a corresponding scope. The scope chain is the bridge connecting these scopes. Its role is related to the program's search for a variable identifier:

1) The JS interpreter adds the scope to the scope chain in the calling Order (the scope that enters early like a stack will be at the bottom of the scope chain );

2) then, when the program looks for a variable identifier, it enters the first index in the scope chain and searches for the variable identifier;

3) If this identifier is not found, go to the next index to continue searching;

4) if the ID is found, the ID and its value are returned;

5) if the last index still fails to find the identifier, create the identifier on the last index and set its value to null. Then, return the identifier and value.

PS: the prerequisite for the above step 5th is that the identifier is on the left side of the expression of the value assignment operator.

Therefore, when you do not use var to declare a variable and directly use it for initialization (simple value assignment), JS will automatically create the null value identifier for you, and allows it to smoothly execute the value assignment statement.

Variable and scope chain

From the above description, we can easily see the relationship between variables and the scope chain. As long as the program needs to find variables, it must use the scope chain. The closure problem mentioned above comes from this. Let's recall the previous sample code:

 

1 var abc = function (y ){

2 var x = y; // This is a local variable.

3 return function (){

4 alert (x ++); // here, the x of the local variable of the first-level function in the closure feature is called and operated on it.

5 alert (y --); // The referenced parameter variable is also a free variable.

6 }}( 5); // Initialization

7 abc (); // "5" "5"

8 abc (); // "6" "4"

9 abc (); // "7" "3"

10 alert (x); // error! "X" is not defined!

 


What are the problems in the scope chain in javascript?

This is a problem of variable scope. Limited to the js theory I have mastered, I can only explain it to you.
Js variables are the principle of first defining and then Accessing. If there is no definition, the value becomes a global variable,
For example, name = "global variable" defines global variables, which is equivalent to window. name = "global variable ". That is, you can access this variable anywhere in the world. However, in a function, a function is equivalent to a box. The methods in the box can access the variables outside, but the variables declared in the box itself cannot be accessed by the outside. This is the scope of variables that everyone can talk about. Not hard to understand
Function (){
Var name = "local variable"
}
Alert (name) // undefined
Because name is defined in the function and private to the function, external access is not allowed.
But why is the following result?
Function (){
Alert (name) // The output is 'undefined'
Var name = "local variable" // The variable is declared here
}
First, the browser has Parsed the entire function () {}, that is, the entire function has been read.
As mentioned above, js variables are defined and used first. Because the function searches for variables from the inside out,
That is, the system first looks for the variable inside itself, whether it has been defined, if not, to the outside.
The above code can be understood as follows:
When js parses it to alert (name), because function already knows that the name variable already exists in it, the name variable will not be searched externally, however, because js Parsing is performed from top to bottom, that is, var name = "local variable" has not been resolved, the name has a name but no value (with a name without a real name) undefined.

What are the problems in the scope chain in javascript?

This is a problem of variable scope. Limited to the js theory I have mastered, I can only explain it to you.
Js variables are the principle of first defining and then Accessing. If there is no definition, the value becomes a global variable,
For example, name = "global variable" defines global variables, which is equivalent to window. name = "global variable ". That is, you can access this variable anywhere in the world. However, in a function, a function is equivalent to a box. The methods in the box can access the variables outside, but the variables declared in the box itself cannot be accessed by the outside. This is the scope of variables that everyone can talk about. Not hard to understand
Function (){
Var name = "local variable"
}
Alert (name) // undefined
Because name is defined in the function and private to the function, external access is not allowed.
But why is the following result?
Function (){
Alert (name) // The output is 'undefined'
Var name = "local variable" // The variable is declared here
}
First, the browser has Parsed the entire function () {}, that is, the entire function has been read.
As mentioned above, js variables are defined and used first. Because the function searches for variables from the inside out,
That is, the system first looks for the variable inside itself, whether it has been defined, if not, to the outside.
The above code can be understood as follows:
When js parses it to alert (name), because function already knows that the name variable already exists in it, the name variable will not be searched externally, however, because js Parsing is performed from top to bottom, that is, var name = "local variable" has not been resolved, the name has a name but no value (with a name without a real name) undefined.

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.