JavaScript execution Environment and scope detailed _javascript tips

Source: Internet
Author: User
Tags define function joins

Recently reread "JavaScript Advanced Programming 3", think should write some blog to record some knowledge of learning, or forget it. Today to summarize is the JS execution environment and scope.

First, the execution environment.

I. Implementation of the Environment
In the book concept, the execution environment defines the other data that a variable or function has access to, determining their respective behavior. Each execution environment has a variable object associated with it. All variables and functions defined in the environment are saved in this object. Although we cannot access this object while writing code, the parser uses it in the background when it processes the data.

  An execution Environment is a concept, a mechanism that defines whether a variable or function has access to other data

In JavaScript, the JavaScript code that can be executed is divided into three types:
1. Global code, that is, the whole, not in any function, such as: A JS file, embedded in the HTML page of the JS code.
2. Eval code, which is dynamically executed with the Eval () function.
3. Function code, that is, functions in user-defined functions JS code.

Skips the Eval Code, saying only the global execution environment and function execution environment.

1. Global Environment:

The global environment is one of the outermost execution environments. The global execution environment is considered a Window object. Therefore, all global variables and functions are created as properties and methods of the Window object. When the code is loaded into the browser, the global execution environment is created (the global execution environment is destroyed when we close the Web page or the browser). For example, in a page, the first time you load the JS code to create a global execution environment.

This is also why closures have a flaw in memory leaks. Because the external function in the closure is considered the global environment. So it will not be destroyed and kept in memory.

2. Function Execution Environment

Each function has its own execution environment, and when executed into a function, the execution environment of the function is pushed into the top of a stack of execution environments and gets execution power. When this function completes, its execution environment is removed from the top of the stack, and the execution power is returned to the execution environment before it is executed. This is the execution stream in the ECMAScript program.

You can also interpret this: when a JavaScript function is invoked, the function enters the execution environment corresponding to the function. If another function is called, a new execution environment is created, and the execution process is in that environment during the function call. When the called function returns, the execution returns to the original execution environment. As a result, the running JavaScript code forms a stack of execution environments.

  When the function is invoked the local environment of the function is created (after the execution of the code within the function, the environment is destroyed, and all the variables and function definitions stored therein are destroyed).

2-1 definition Period

When a function is defined, a [[scope]] property is created, which corresponds to a list of objects that can only be accessed by JavaScript and cannot be accessed through syntax.

(Scope is the meaning of the scope.) )

We define a global function A, then the a function creates a [[scope]] property. At this point, the [[scope]] contains only the global object, "globally."

And if, we define a B function within a, and the B function also creates a [[scope]] property, and B's [[Scope]] property contains two objects, one is the active object of a, activation object, one is a global object, and the active object of a is in the front, Global objects are in the back row.

In short, the order of the list of objects in the [Scope] property of a function is the activation object of the upper-level function, and then the upper layer, up to the outermost global object.

Here is the sample code: A only one scope,b has two scope

External functions function
A () {
  var somevar;
  
  Intrinsic functions function
 B () {
   var somevar;
  }
}

2-2 Implementation Period

When a function is executed, it is entered into the execution environment of the function, first creating its own active object "Activation Object" (This object contains this, parameters (arguments), local variables (including named arguments) Definition and the scope chain of a variable object [[scope chain]], then copy [scope] of this execution environment to [[scope chain]], and finally push the active object to the top of [[Scope chain]]. In this way [[scope chain]] is an ordered stack that guarantees orderly access to all variables and objects that the execution environment has access to.

The first step page is loaded into the global execution environment global executing context and global activity image//Definition global [[scope]], only contains Window objects//scan global definition variables and Function objects: color "undefined",
ChangeColor "FD creates changecolor [[scope]], which contains only global active objects", and joins the window so that global variables and global function objects are defined as properties of Windows.

The program has been defined so that ChangeColor () can be executed anywhere in this execution environment, and color has been defined, but its value is undefined//second step color assignment "Blue" var color = "Blue"; It is not required to assign a value, it is the reference itself function ChangeColor () {//Fourth Step into the ChangeColor execution Environment//copy ChangeColor [[[Scope]] to scope chain//Create activity object, Scan defines variables and defines functions, anothercolor "undefined" and swapcolors "FD Create swapcolors [[scope]] to join ChangeColor active objects and global active objects" to the active object, The active object also joins the arguments and this//activity object to push the scope chain Top//program has been defined so that swapcolors () can be executed anywhere in this execution environment, and Anothercolor has been defined.
 
 But its value is undefined//fifth Anothercolor Assignment "Red" var anothercolor = "Red";
  It is not required to assign a value, it is the reference itself function swapcolors () {//Seventh Step into the Swapcolors execution environment, create its active object//Copy swapcolors [[scope]] to scope chain Scans define variables and define function objects, add variables tempcolor "undefined" to the active object, and arguments and this//activity objects push into scope chain top//Eighth Tempcolor assignment Anothercolo R,anothercolor and color will followScope chain is found and continues to execute var tempcolor = Anothercolor;
   Anothercolor = color; 
 color = Tempcolor;
The sixth step is to execute swapcolors and enter its execution environment swapcolors ();

 The third step is to execute changecolor and enter its execution environment ChangeColor ();

2-3 Access identifiers:

When the JS code is executed, an identifier is encountered, and the search is performed in the scope chain of the execution context (Execution contexts) based on the name of the identifier. Starts from the first object in the scope chain (the function's activation object) and, if not found, searches for the next object in the scope chain, and so forth, until the definition of the identifier is found. If the last object in the scope is not found after searching the global object, then an error is thrown, prompting undefined.

Ii. scope/scope Chain (Scope/scope chain)

When the code executes in an environment, a scope chain is created. The purpose of a scope chain is to ensure orderly access to all variables and functions that have access to the execution environment. The entire scope chain is a linked list that is constructed according to rules by variable objects at different execution locations. The front end of the scope chain is always the variable object in the environment where the code is currently executing.

If the environment is a function, its active object (activation object) is used as the variable object. The active object contains only one variable at the beginning, which is the arguments object within the function. The next variable object in the scope chain comes from the containing environment of the function, and the next variable object comes from the next containing environment. This continues to the global execution environment, where the variable object of the global execution environment is always the last object in the scope chain.

As shown in the figure:

Examples in the book:

 var color= "Blue";
 function ChangeColor () {
 var anothercolor= "Red";
 function Swapcolors () {
 var tempcolor=anothercolor;
 Anothercolor=color;
 Color=tempcolor;
  Todo something  
  }
 swapcolors ();
}
ChangeColor ();
 There is no access to Tempcolor and Anocolor, but you can access color;
Alert ("Color is now" +color);

Through the above analysis, we can learn that the internal environment can access all the external environment through the scope chain, but the external environment can not access any variables and functions in the internal environment.

These environments are linear and sequential. Each environment can search the scope chain up to query for variables and function names, but no environment can enter another execution environment by searching the scope chain down.

For the Swapcolor () function of the above example, the scope chain includes the variable object of Swapcolor (), the ChangeColor () variable object, and the global object. The local Environment of Swapcolor () first searches for the variable and function names in its own variable object, and then searches for the changecolor scope chain up .... Analogy However, the ChangeColor () function is unable to access the variable in the Swapcolor

revelation: use local variables as much as possible to reduce search time

1, no block-level scope

Unlike C, C + +, and Java, Javscript does not have block-level scopes. Look at the following code:

if (true) {
  var myvar = ' John '; 
 }
 alert (myvar);//John

If there is a block-level scope, the outside is inaccessible to MyVar. And look at the bottom.

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

For a block-level scope language, such as Java or C # code, I is a variable that is initialized for, and is not accessible for the purpose of. Because I only exists in the for cycle weight, all the variables in the for are destroyed after the for loop is run. This is not true in JavaScript, where the variable declaration is added to the current execution environment (this is the global execution environment), so after the for loop, the variable I still exists in the execution environment outside the loop. As a result, 10 is output.

2. Declaring variables

When you declare a variable by using VAR, the variable is automatically added to the nearest available environment. For the inside of a function, the closest environment is the local variable of the function. If Var is not used when the variable is initialized, the variable is automatically added to the global function.

The code is as follows:

var name = "Xiaoming";
function GetName () {
 alert (name);//' undefined '
 var name = ' small yellow ';
 alert (name); Small yellow
}
getName ()

Why is the first name undefined? This is because the JavaScript parser, which enters a function execution environment, scans Var and function first.

The equivalent of a var or function declaration declaration is promoted to the top of the execution environment.

In other words, when we enter our GetName function, the identifier lookup mechanism finds Var, and the name of the lookup is the local variable name, not the global name, because the name in the function is elevated to the top.

The code above will be parsed into the following:

var name = "Xiaoming";
function GetName () {
 var name;
 alert (name); ' Undefined '
 var name = ' small yellow ';
 alert (name); Small yellow
}
getName ()

Extend scope chain:

Although there are only two types of execution environment-global scope and function scope-there is some way to extend the scope chain. Because some statements can add a temporary variable object at the top of the scope chain.
This behavior can occur in two ways:
1, Try-catch Statement of the catch block;
2, with statement;

The above is the entire content of this article, I hope that you learn to understand the JavaScript implementation environment and scope to help.

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.