JavaScript Chapter-----Execution Environment and scope

Source: Internet
Author: User
Tags getcolor

The execution environment is one of the most important concepts in JavaScript. The execution environment defines the other data that a variable or function has access to, and determines their respective behavior. Each execution environment has a variable object associated with it, and all variables and functions defined in the environment are stored in the object.

The global execution environment is one of the outermost execution environments, and the objects that represent the execution environment are different depending on the hosting environment in which the ECMAScript implementation resides. In a Web browser, the global execution environment is considered a Window object because all global variables and functions are created as properties and methods of the Window object. After all code in an execution environment is executed, the environment is destroyed, and all the variables and function definitions stored therein are destroyed.

Each function has its own execution environment. When the execution flow enters a function, the environment of the function is pushed into an environment stack. After the function executes, the stack pops up its environment and returns control to the previous execution environment. The execution flow in the ECMAScript program is controlled by this convenient mechanism.

When code executes in an environment, a scope chain of variable objects is created. The purpose of a scope chain is to provide orderly access to all variables and functions that have access to the execution environment. The front end of the scope chain, which is always the variable object for the environment in which the code is currently executing. If the environment is a function, its active object is used as a variable object. The active object initially contains only one variable, the arguments object. The next variable object in the scope chain comes from the containing environment, while the next variable object is from the next containing environment. This continues to the global execution environment. The variable object for the global execution environment is always the last object in the scope chain.

Identifier parsing is the process of searching identifiers one level at a scope chain. The search process always starts at the front end of the scope chain and then goes backwards backward until the identifier is found.

1 {2   varcolor = ' Blue ';3   functionChangeColor () {4     varAnothercolor = ' Red ';5     functionswapcolors () {6       varTempcolor =Anothercolor;7Anothercolor =color;8color =Tempcolor;9       //swapcolors () Local environment, where you can access Color,anothercolor and TempcolorTen     } One     //changecolor () Local environment, where you can access color and anothercolor, but not access Tempcolor A swapcolors (); -   } -   //Global Environment window, where you can access only the color the ChangeColor (); -}

The above code involves a total of 3 execution environments: The global Environment, the ChangeColor () local environment, and the local environment of the swapcolors (). There is a variable color and a function changecolor () in the global environment. The local Environment of ChangeColor () has a variable named Anothercolor and a function named Swapcolors (), but it can also access the variable color in the global environment. The local Environment of Swapcolors () has a variable tempcolor, which can only be accessed in this environment. Local environments, whether global or ChangeColor (), do not have access to tempcolor. However, within swapcolors (), you can access all the variables in the other two environments, because those two environments are its parent execution environment. The following diagram shows the scope chain structure of the above code.

Extend the scope chain

The following statement can temporarily add a variable object to the front of the scope chain, and the variable object is removed after the code is executed.

      • The catch block of the Try-catch statement;
      • With statement;

Both statements add a variable object at the front end of the scope. For the WITH statement, the developed object is added to the scope chain. For a catch statement, a new variable object is created that contains the declaration of the thrown error object.

 1  { 2  function   BuildUrl () { 3  var  qs = '? debug=true ' ;
    4  with   5  var  url = href + Qs;  6  }  7  return   URL;  8  }  9  }

In the above code, the WITH statement accepts the location object, so its variable object contains all the properties and methods of the Location object, and the variable object is added to the front end of the scope chain. A variable QS is defined in the BuildUrl () function. When the variable href is referenced in the WITH statement (actually referencing location.href), it can be found in the variable object of the current execution environment. When referring to the variable QS, the variable that is defined in BuildUrl () is referenced in the variable object in the function environment. As for the inside of the WITH statement, a variable named URL is defined, so the URL becomes part of the function execution environment, so it can be returned as the value of the function.

No block-level scopes

In other languages of Class C, blocks of code that are enclosed by curly braces have their own scopes, that is, block-level scopes. In the case of a block-scoped language, the code inside the block is destroyed after the block has finished executing. For ECMAScript, however, there is no block-level scope, only the function scope, and the variable object is destroyed only after the function block has been executed.

declaring variables

Variables declared with Var are automatically added to the closest environment. Inside the function, the closest environment is the local environment of the function. In the With statement, the closest environment is the function environment. If you initialize a variable without using the var declaration, the variable is automatically added to the global environment.

1 {2   functionAdd (NUM1, num2) {3     varsum = NUM1 +num2;4     returnsum;5   }6   varresult = Add (10, 20);// -7   //console.log (sum);//error, sum defined in the local scope of add (), not accessible in global scope8   functionadd1 (NUM1, num2) {9SUM1 = Num1 + num2;//variables that are not declared with Var are added to the global scopeTen     returnsum1; One   } A   varRESULT1 = ADD1 (10, 30);// + -Console.log (SUM1);//40, the ability to access the sum1 that is added to the global scope -}
Query identifiers

When you reference an identifier in an environment for reading or writing, you must search to determine what the identifier actually represents. The search process starts at the front end of the scope chain and queries the identifiers that match the given name upwards. If the identifier is found in the local environment, the search process stops and the variable is ready. If the variable name is not found in the local environment, it continues to search up the scope chain. The search process goes back to the variable object of the global environment. If the identifier is not found in the global environment, it means that the variable is not yet declared.

In this search process, if there is a local definition of the variable, the search stops automatically and no longer enters another variable object. In other words, identifiers in the parent environment are not used if there is an identifier with the same name in the local environment.

 1  { 2  var  color = ' Blue ' ;  3  function   GetColor () { 4  var  color = ' Red '  5  return   color;  6  }  7  Console.log (GetColor ()); //  "Red"  8 } 

In the preceding code, a local variable named color is declared in the GetColor () function. When the function is called, the variable is declared. When the second line of code in the function executes, it means that the value of the variable color must be found and returned. The search process begins with a local environment, and a variable named color is found here with the value "red". Because the variable is already found, the search stops immediately, the return statement uses the local variable, and the function returns "Red". That is, any code that follows the declaration of a local variable color cannot access the global color variable without using Window.color. Show the entire search process.

JavaScript Chapter-----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.