javascript-variables and scope chains

Source: Internet
Author: User
Tags script tag

jquery Fragment:

1 var

2/References to window, and allows munging its name.

3 window = this,

4/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

One-by-one jQuery = Window.jquery = window.$ = function (selector, context) {

//The JQuery object is actually just the Init constructor ' enhanced '

Return to New JQuery.fn.init (selector, context);

14},

15

+/A simple-to-check for HTML strings or ID strings

+/(both of which we optimize for)

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

//Is it a simple selector

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

Starting from this section, we peel off jquery's cloak and see what's hidden inside. As mentioned in the previous section, this implementation is definitely not a closure if you look at the outer-layer anonymous function and don't look at the implementation. However, if the implementation of jquery is added, this must be a closure application. In order to understand the closure application, it is essential to understand the foundation of a high-rise building on the ground. And this section, the fragment that we encounter, is where this foundation is--the variable. (Although this fragment contains many knowledge points, please allow me to slowly locutionary.) )

declaring variables

The English name of the variable is variable, and the first three letters are the keyword--var of the variable we declared in JS. So, let's start by looking at how to declare a variable:

1/*

2 * The format of the declared variable is

3 * var variable name initialize variable expression list (optional)

4 */

5 var a=1, B, c= "test", d=a+b;//although B is not initialized yet, the declaration is legal

6 alert (a);//"1"

7 alert (b);//"Undefined"

8 alert (c);//"Test"

9 alert (d);//"NaN"

Alert (e);//A compilation error is raised here: "E" is undefined

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

As shown in the example above, declaring a variable requires the use of the VAR keyword, followed by the name of the variable after the space. While declaring variables, we can also choose to help initialize the variables. The initialized value can be any type of value or expression, but if you attempt to initialize with an undefined variable name, the JS compiler will determine that a compilation error has occurred and prevent the program from continuing to run down. Whether you initialize a declared variable or not, you can continue declaring the second variable without using the var keyword. All you need is an operator ",". (about operators are discussed in detail in a later section.) But when you do not initialize a declared variable, the variable will be given the value "undefined"--undefined is also one of the intrinsic types of JS. The operators used in PS:JS must be half-width English characters, even spaces.

Duplicate declared variables?!

What happens when we declare a variable and then declare it again in the subsequent code? In many other languages, this can cause duplicate definitions, but in JS, this is completely legal. Also, because JS is a weak data type, variables can be given any type of value. Take a look at the following example:

1 var a=1;

2 alert (typeof a); "Number"

3 Var A;

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 fourth a an object?

To answer the first question, let's first understand how the declaration of a variable works. And the second question, we will put him in the next section to discuss again.

Working steps for VAR variable declaration

When we use the VAR keyword to declare a variable, the JS interpreter will do the following:

1) Pre-compiling the VAR keyword within all non-function blocks in the JavaScript code block;

2) Generate Variable name identification and allocate space at the scope where it resides;

3) Run to the first var keyword line in code order;

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

5) Each calculation of an initialization expression, the result of its calculation is assigned to the corresponding declaration variable;

6) Continue to run the following code to the next var keyword;

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

8) Continue compiling to run the next block of code.

PS:JS will run a section of JS code in a block of code, which is a script tag.

Because of the way VAR works, the interpreter is virtually invisible to the VAR keyword when the program executes. He performs only the assignment of the initialization expression-so the answer to question A is that the third sentence in the example actually does nothing. So you don't have to worry about any duplicate variable names in your code. What you really need to worry about is whether the value of the variable generated by the initialization statement changes as you expect. In addition, do not attempt to use reserved words as variable names. This is a specification that must be followed in almost all languages.

Also, the working steps for declaring variables in a function block are similar, but the difference is that they are created when the function is run.

Variable declaration without Var?!

Many friends should have this experience-"We do not need to use VAR to declare variables can also be directly assigned!" ”。 This is because when the JS interpreter encounters an assignment expression, it will first look in the scope chain to see if the variable is declared. If the variable is not declared, it is implicitly coerced to declare it in the global scope, and assigns the value of the expression to the variable.

But why on Earth is this so? In fact, everything is derived from the combination of variables ' acquiring rules and scope chains plus the catalysis of the assignment operator.

Scope chain

Each runtime context has a scope corresponding to it. And the scope chain is the bridge that connects these scopes together. Its function is related to the program looking for a variable identifier:

1) The JS interpreter adds the scope to the scope chain in the order in which it is called (the scope of the stack-like entry is at the bottom of the scope chain);

2) then enter the first index in the scope chain when the program looks for a variable identifier, and look for the variable identifier;

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

4) If the identity has been found, the identity and its value are returned;

5) When the search to the last index still fails to find the identity, the identity is created on the last index and the value is null, and the identity and value are returned.

PS: The 5th step above occurs if the identifier is on the left side of an assignment operator expression.

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

Variables and scope chains

From the above description, we can easily see the relationship between the variable and the scope chain. As long as the program needs to look for variables, it must pass through the scope chain. The closure problem mentioned above is the result of this. Recall our previous sample code:

1 var abc=function (y) {

2 Var x=y;//this is a local variable

3 return function () {

4 alert (x + +);//This is where the first-level function of a local variable in the closure attribute is called and manipulated

5 alert (y--);//argument variable referenced is also a free variable

6}} (5);//initialization

7 ABC ();//"5" "5"

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

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

Ten alert (x);//Error! "X" is undefined!

javascript-variables and scope chains

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.