Introduction to the JavaScript execution environment, scope and garbage collection, and javascript Garbage Collection

Source: Internet
Author: User

Introduction to the JavaScript execution environment, scope and garbage collection, and javascript Garbage Collection

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.

The global execution environment is the most peripheral execution environment. Depending on the host environment where JavaScript implementation is located, the objects in the execution environment are different. In a Web browser, 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.

Variable object:All variables and functions defined in the environment are stored in this object.

Scope chain:When the code is executed in an environment, a scope chain of the variable object 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 front end of the scope chain is always the variable object in the environment where the code is currently executed.

Activity object:The activity object contains only one variable at the beginning, that is, the arguments object. The next variable object in the scope chain comes from the include (external) environment, and the next variable object comes from the next include environment. In this way, the variable objects in the global execution environment are always the last objects in the scope chain.

Identifier Resolution:Identifier Parsing is the process of searching for identifiers at the level of the scope chain. The search process starts from the front end of the scope chain, and then traces back to the end step by step until the identifier is found.

Sample Code:

var color = "blue";function changeColor() {  if (color === "blue") {    color = "red";  } else {    color = "blue";  }}changeColor();alert("Color is now " + color);

The scope chain of function changeColor () contains two objects: its own variable object (which defines the arguments object) and the variable object of the global variable. You can access the variable color in the function because it can be found in the scope chain.

In addition, variables defined in the local scope can be used with global variables in the local environment. For example:

Var color = "blue"; function changeColor () {var anotherColor = "red"; function swapColors () {var tempColor = anotherColor; anotherColor = color; color = tempColor; // here you can access color, anotherColor, and tempColor} // here you can access color, anotherColor, and tempColor swapColors ();} // you can only access colorchangeColor () here ();

The preceding Code is applicable to three execution environments: Global Environment, changeColor () handle environment, and swapColors () local environment.

The global variable includes a variable color and a function changeColor (). The local variable of changeColor () contains a variable anotherColor and a function swapColors (), which can access the color in the global variable. The local variable of swapColors () contains the variable tempColor. In swapColors (), you can access the color in the global variables or the anotherColor variable, because the two environments are their parent execution environments. The scope chain in the above example is:

Where,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. The relationship between environment variables is linear and ordered. Each variable can only search for the scope chain from the upper level and query the variables and function names. That is, the variable or function name is first queried in the current action. If no query is performed for the scope chain at the upper level, until the top-level scope. However, no environment can search down the scope chain and enter another execution environment.

Function parameters are also treated as variables, so their access rules are the same as other variables in the execution environment.

1. extend the scope chain

When the execution flow enters any of the following statements, the scope chain will be extended:

• Catch blocks of try-catch statements

• With statement

These two statements Add a variable object to the front-end of the scope.

For the with statement, the specified variable is added to the scope chain. For a catch statement, a new variable object is created, including the declaration of the thrown error object.

For example:

function buildUrl() {  var qs = "?debug=true";  with(location) {    var url = href + qs;  }  return url;}

The with statement receives the location object. Therefore, the variable object contains the attributes and methods used by the location object. This variable object is added to the frontend of the scope chain. When the href variable is referenced in the with statement (location. href is actually referenced), it can be found in the current environment variable. When the qs variable is referenced, it refers to the variable defined in buildUrl (), which is located in the function environment variable object. As for the with statement, a variable named url is defined, so url becomes part of the function execution environment and can be returned as the function value.

2. No block-level scope

In JavaScript, closed curly braces do not have their own scopes. See the following code:

 

if(true) {  var color = "blue";}alert(color);  // "blue"

In JavaScript, the variable Declaration created by the if/for statement adds the variable to the current execution environment. For example:

for(var i = 0; i < 10; i++) {  doSomething(i);}alert(i);// 10

Garbage Collection

Similar to Java, JavaScript also has an automatic garbage collection mechanism. The Execution Environment manages the memory used during code execution. When writing a program, you do not need to worry about memory usage. The necessary memory allocation and useless memory recycling fully implement automatic management. The mechanism of garbage collection is to find out the variables that are no longer in use, and then release the memory occupied by them. To this end, the garbage collector periodically performs this operation at a fixed interval (or a scheduled collection time during code execution.

Before performing garbage collection, you must determine whether the resource is useless and Mark unused variables for future memory recovery. Policies used to identify useless variables usually have two implementations.

1 Mark Clear

The most common method of garbage collection in JavaScript is to mark and clear. When a variable enters the environment, it is marked as "entering the environment". When the variable leaves the environment, it is marked as "leaving the environment ". The garbage collector will mark all the variables used during running. Then, it removes the environment variables and the variables referenced by the environment variables. The variables marked after this are considered as the variables to be deleted. The Garbage Collector completes the memory cleanup, destroys the marked values, and recycles the memory space they occupy.

2. Reference count

Reference count refers to the number of times each value of a trail is referenced. When a variable is declared and a reference type value is assigned to the variable, the number of times this value is referenced is 1. If the same value is assigned to another variable, the number of times the value is referenced increases by 1. On the contrary, if another variable is obtained from the variable that contains this value reference, the number of references to this value is reduced by 1. When the number of times this variable is referenced is 0, it indicates that there is no way to reference this variable, so we can reclaim its memory space. When the Garbage Collector runs next time, the memory occupied by the zero reference count will be reclaimed.

A problem with reference count is that it may cause circular reference. For example:

function problem() {  var objA = new Object();  var objB = new Object();  objA.someOtherObj = objB;  objB.someOtherObj = objA;}

In the preceding example, objA and objB are referenced by attributes. After the function is executed, objA and objB will continue to exist, and their reference count will not be 0. In this case, the memory occupied by objA and objB cannot be recycled.

The above discussion about JavaScript: The execution environment, scope, and garbage collection are all the content shared by Alibaba Cloud. I hope to give you a reference and support for the customer's home.

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.