Learn JavaScript from the beginning (ix)-Execution environment and scope

Source: Internet
Author: User

Original: Learn JavaScript from the beginning (ix)--Execution environment and scope

The execution environment: Defines the other data that variables or functions have access to, and determines their respective behavior. Each execution environment has a variable object associated with it.

Variable object: Holds variables and functions defined in the environment.

Scope chain: Ensures an orderly access to all variables and functions that the execution environment is authorized to access.

identifier parsing: The process of searching identifiers at a level along the scope chain.

Examples illustrate the execution environment, variable objects, and scope chains:

1<script type= "Text/javascript" >2         varcolor = "Blue"; 3         functionChangeColor () {4             varAnothercolor = "Red"; 5             functionswapcolors () {6                 varTempcolor =Anothercolor;7Anothercolor =color;8color =Tempcolor; 9                 //color, Anothercolor, TempcolorTen             }         One             //Color and Anothercolor A swapcolors (); -         }         - ChangeColor (); the         //Color -Alert ("Color is now" +color);  -</script>

The execution environment and execution flow in the above example:

The painting is not good, please crossing forgive me ....

Scope Chain:

Execution environment is like a box, the global environment is the outermost box, which contains a lot of functions of the box, each function of the box contains its own sub-function box, open the time from the outside and in turn linearly open, if only open the global environment of the box, Then you can only see things outside of the box in the global environment, such as the global box has two sub-boxes (the first box has biscuits, the second box has cakes) and a small toy, then you can only get toys, but not to get biscuits and cakes. If you continue to open the first sub-box of the global box, you can get the toys in the global variables and get the biscuits, but there is no way to get the cake.

Second, scope

2.1 Extending the scope chain

Although there are only two types of execution environments-global scope and function scope-there is a way to extend the scope chain. Because some statements can add a temporary variable object at the top of the scope chain. There are two situations where this behavior occurs: 1, the catch block of the Try-catch statement, and a new variable object that contains the declaration of the thrown error object. 2, with statement; Adds the specified object to the scope chain.
1<script type= "Text/javascript" >2         functionBuildUrl () {3             varQS = "? Debug=true"; 4              with(location) {5                 varurl = href +QS; 6             }        7             returnURL;8         }9         varresult =BuildUrl ();Ten alert (result);  One</script>

With will include all the properties and methods of the location object in the variable object, and join to the top of the scope chain. Accessing the HREF is actually location.href.

Detailed with statement:

1 functionInitui () {2     with(document) {3         varBD =Body,4Links = getElementsByTagName ("a"),5i = 0,6Len =links.length;7          while(i<Len) {8Update (links[i++]);9         }TengetElementById ("Go-btn"). onclick =function(){ One start (); A         }; -Bd.classname = "Active" -    } the}

Using the WITH statement here avoids writing the document multiple times, looks more efficient, and actually produces performance problems.

When a code flow executes into a with expression, the scope chain of the execution environment is temporarily changed , and the variable object with the with is created to be added to the front end of the scope chain, which means that all local variables of the function are pushed into the variable object in the second scope chain. So the cost of access is even higher.

Therefore, you should avoid using the WITH statement in your program, and in this case, you can improve performance by simply storing the document in a local variable.

1 functionInitui () {2         varDoc=Document3         varBD =Doc.body,4Links = doc.getelementsbytagname ("a"),5i = 0,6Len =links.length;7          while(i<Len) {8Update (links[i++]);9         }TenDoc.getelementbyid ("Go-btn"). onclick =function(){ One start (); A         }; -Bd.classname = "Active" -  the}

The catch statement is detailed:

When an error occurs in a try code block, the execution jumps to the catch statement, and then pushes the exception object into a Mutable object and puts it in the scope's head. Inside a catch code block, all local variables of the function are placed in the second scope chain object.

1 Try {      2dosomething ();   3 }catch(ex) {4      5//6   

Note that once the Catch statement finishes executing, the scope chain opportunity returns to the previous state. Try-catch statements are useful in code debugging and exception handling, so it is not recommended to avoid them altogether. You can reduce the performance impact of catch statements by optimizing your code. A good pattern is to delegate the error to a function handler, for example:

1 Try {23  } Catch  4//5

After the optimized code, the HandleError method is the only code executed in the Catch clause. The function receives the exception object as a parameter, so you can handle the error more flexibly and uniformly. Because only one statement is executed and there is no access to local variables, temporary changes to the scope chain do not affect code performance.

2.2 No block-level scope

The javscript does not have a block-level scope. Look at the following code:

if (true) {        var myvar = "Jack";        }    alert (myvar);//Jack

As we discussed above, if there is a block-level scope, the external is not accessible to myvar. Look at the bottom again.

for (Var i=0;i<5;i++) {            console.log (i)            }                alert (i);//5

For a block-scoped language, I is a for-initialized variable that is not accessible outside of the for, which proves that JavaScript is not block-scoped.

Learn JavaScript from the beginning (ix)-Execution environment and scope

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.