Detailed description of the javascript Execution Environment and scope, and detailed description of javascript

Source: Internet
Author: User
Tags define function

Detailed description of the javascript Execution Environment and scope, and detailed description of javascript

I recently reread "javascript advanced programming 3" and thought I should write some blogs to record some of my learning knowledge. Otherwise I will forget it. Today we will summarize the js execution environment and scope.

First, let's talk about the execution environment

I. Execution Environment
In the book, the execution environment defines other data that variables or functions have the right to access and determines their respective actions. Each execution environment has a variable object associated with it. All variables and functions defined in the environment are stored in this object. Although we cannot access this object when writing code, the parser will use it in the background when processing data.

An execution environment is a concept and a mechanism that defines whether a variable or function has the right to access other data.

In javascript, JavaScript code can be executed in three types:
1. Global Code, that is, Global Code that is not in any function, such as a js file and js Code embedded in the HTML page.
2. Eval Code: JS Code dynamically executed using the eval () function.
3. Function Code, that is, the JS Code of the Function body in the User-Defined Function.

Skip the Eval Code, which only indicates the global execution environment and function execution environment.

1. Global Environment:

The global environment is the most peripheral execution environment. 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 only when the webpage or browser is closed ). For example, create a global execution environment when loading JS Code for the first time on a page.

This is also why the closure has a disadvantage of Memory leakage. Because the external functions in the closure are treated as the global environment. So it will not be destroyed and will be stored in the memory all the time.

2. Function execution environment

Each function has its own execution environment. When the execution enters a function, the execution environment of the function will be pushed to the top of an execution environment stack and get the execution right. After the function is executed, its execution environment is deleted from the top of the stack and the execution right is returned to the previous execution environment. This is the execution stream in the ECMAScript program.

It can also be interpreted as follows: When a JavaScript function is called, 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 this environment during the function call. When the called function returns, the execution process returns the original execution environment. Therefore, the running JavaScript code constitutes an execution environment stack.

When a function is called, the local environment of the function is created. (After the code in the function is executed, the environment is destroyed, all variables and function definitions stored in them are also destroyed ).

2-1 Definition Period

When a function is defined, a [[scope] attribute is created. This object corresponds to a list of objects. Objects in the list can only be accessed within javascript and cannot be accessed through syntax.

(Scope means scope .)

If we define A global function A, function A creates A [[scope] attribute of function. In this case, [[scope] only contains the Global Object ].

If we define A function B within function A, function B will also create A [[scope] attribute. The [[scope] attribute of function B contains two objects, one is activity Object Activation Object of A, the other is global Object, activity Object of A is in front, and global Object is in the back.

In short, the list of objects in the [Scope] attribute of a function is the Activation Object of the previous function, and then the Global Object of the upper layer until the outermost layer.

The following is the sample code: A has only one scope, and B has two scopes.

// External function A () {var somevar; // internal function B () {var somevar ;}}

2-2 execution period

When a function is executed, it enters the execution environment of the function. First, it creates its own activity Object [Activation Object] (this Object contains this and arguments) and the scope chain of a variable object [[scope chain]. Then, copy the [scope] of the execution environment to [[scope chain] in sequence, and push the activity object to the top of [[scope chain. [Scope chain] is an ordered stack, which ensures the orderly access to all variables and objects that the execution environment has the right to access.

// Step 1 load the global execution environment global executing context and global activity image // define the global [scope], only Window objects are included. // global variables and function objects are scanned. color [undefined] And changecolor [FD creates changecolor [scope]. at this time, only global activity objects are included in the window. Therefore, global variables and global function objects are defined as window attributes. // The program has been defined, so changecolor () can be executed anywhere in the execution environment, and color has been defined, however, its value is undefined // In the second step, the color value is assigned "blue" var color = "blue"; // it does not need to be assigned a value, and it refers to its own function changecolor () {// Step 4: Import changecolor's execution environment // copy changecolor's [[scope] to scope chain // create activity objects, scan for definition variables and define functions, anothercolor [undefined] And swapcolors [FD creates swapcolors [[scope] and adds changecolor activity objects and global activity objects to activity objects, the arguments and this // activity object must be added to the activity object and pushed to the top of the scope chain. // The program has been defined, so swapcolors () can be executed anywhere in the execution environment (), anothercolor has been defined, but its value is undefined // The Fifth anothercolor value is "red" var anothercolor = "red"; // it does not need to be assigned a value, it is to reference its function swapcolors () {// Step 7 to enter the swapcolors execution environment, create its activity object // copy [[scope] of swapcolors to scope chain // scan to define variables and define function objects, the variables tempcolor [undefined] and arguments and this // The activity object are added to the activity object and pushed to the top of the scope chain. // The value of tempcolor in Step 8 is anothercolor. anothercolor and color are found along the scope chain, run var tempcolor = anothercolor; anothercolor = color; color = tempcolor;} // step 6, run swapcolors, and enter swapcolors ();} // execute changecolor in step 3 to enter its execution environment changecolor ();

2-3 Access identifier:

When an identifier is encountered during the Execution of js code, it is searched in the scope chain of the Execution Context based on the identifier name. Starting from the first Object of the scope chain (the Activation Object of the function), if not found, search for the next Object in the scope chain until the identifier definition is found. If the last Object in the search scope, that is, the Global Object, is not found, an error is thrown, prompting undefined.

2. Scope/Scope Chain (Scope/Scope Chain)

When code is executed in an environment, a scope chain is created. The purpose of the scope chain is to ensure orderly access to all variables and functions that the execution environment has the right to access. The whole scope chain is a linked list built by the variable objects at different execution locations according to the rules. The frontend of the scope chain is always the variable object in the environment where the code is currently being executed.

If the environment is a function, the activation object is used as the variable object. The activity object contains only one variable at the beginning, which is the arguments object inside the function. The next variable object in the scope chain comes from the function's inclusion environment, and the next variable object comes from the next inclusion environment. In this way, the Variable Object in the global execution environment is always the last Object in the scope chain.

:

Example in the book:

Var color = "blue"; function changecolor () {var anothercolor = "red"; function swapcolors () {var tempcolor = anothercolor; anothercolor = color; color = tempcolor; // Todo something} swapcolors ();} changecolor (); // tempcolor and anocolor cannot be accessed here; however, color can be accessed; alert ("Color is now" + color );

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

These environments are linear and ordered. Each environment can search for the scope chain to query the variables and function names. However, no environment can search for the scope chain to enter another execution environment.

For the swapcolor () function in the preceding example, its scope chain includes: swapcolor () variable object, changecolor () variable object, and global object. The local environment of swapcolor () starts to search for the Variable and function name in its Variable Object. If the Variable and function name cannot be found, the changecolor scope chain is searched up ..... And so on. However, the changecolor () function cannot access the variables in swapcolor.

Inspiration:Use local variables whenever possible to reduce search time

1. No block-level scope

Unlike C, C ++, and JAVA, Javscript has no block-level scope. See the following code:

If (true) {var myvar = "zhangsan";} alert (myvar); // zhangsan

If there is a block-level scope, myvar cannot be accessed externally. Let's look at the following:

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

For languages with block-level scopes, such as java or c # code, I cannot be accessed outside of for as a variable for initialization. Because I only exists in the for loop weight, after running the for loop, all variables in the for are destroyed. This is not the case in javascript. The variable declaration in for will be added to the current execution environment (the Global execution environment). Therefore, after the for loop is complete, variable I still exists in the execution environment outside the loop. Therefore, 10 is output.

2. Declare Variables

When you declare a variable using var, the variable is automatically added to the nearest available environment. For a function, the closest environment is the local variable of the function. If var is not used during initialization, the variable is automatically added to the global function.

The Code is as follows:

Var name = "Xiao Ming"; function getName () {alert (name); // 'undefined' var name = 'xiao Huang '; alert (name ); // xiaohuang} getName ()

Why is the first name undefined. This is because the javascript parser enters a function execution environment and scans var and function first.

It is equivalent to raising the var or function [function declaration] declaration to the top of the execution environment.

That is to say, when we enter our getName function, the identifier lookup mechanism finds var, And the searched name is the local variable name rather than the global name, because the name in the function is promoted to the top.

The above code will be parsed as follows:

Var name = "Xiao Ming"; function getName () {var name; alert (name); // 'undefined' var name = 'xiao Huang '; alert (name ); // xiaohuang} getName ()
 

Extended scope chain:

Although the execution environment has only two types: global scope and function scope, you can extend the scope chain in some way. Some statements can add a temporary variable object at the top of the scope chain.
This happens in two cases:
1. catch Block of the try-catch statement;
2. with statement;

The above is all the content of this article. I hope it will help you learn and understand the javascript 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.