On JavaScript execution Environment, scope and _javascript techniques of garbage collection

Source: Internet
Author: User
Tags garbage collection memory usage time interval

The execution environment defines other data that a variable or function has access to, determining their respective behavior. Each execution environment has a variable object associated with it.

The global execution environment is one of the outermost execution environments. Depending on the host environment in which the JavaScript implementation resides, the object representing the execution environment is 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 saved in this object.

scope chain: When a contemporary code executes in an environment, it creates a scope chain of variable objects. The purpose of a scope chain is to ensure orderly access to all variables and functions that have access to the execution environment. The front end of the scope chain is always the variable object of the environment in which the currently executing code resides.

Active object: the active object contains only one variable at the beginning, that is, the arguments object. The next variable object in the scope chain comes from the containing (external) environment, and the next variable object comes from the next containing environment. This continues to the global execution environment, and the variable objects of the global execution environment are always the last object in the scope chain.

Identifier Resolution: identifier resolution is the process of searching for identifiers one level down the scope chain. The search process always starts at the front end of the scope chain, and then recursively backtrack backwards 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 the 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 inside a function because it can be found in the scope chain.

In addition, variables defined in local scopes can be used interchangeably with global variables in local environments, examples:

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, no access to Tempcolor
  swapcolors (); 

Only color ChangeColor () can be accessed here
;

The above code covers 3 execution environments: The global Environment, the ChangeColor () handle environment, and the swapcolors () Local environment.

The global variable has a variable color and a function changecolor (). The local variable of ChangeColor () contains a variable anothercolor and a function swapcolors () function that can access the color in the global variable. Swapcolors () has a variable tempcolor in the local variable. You can access the color in the global variable in swapcolors (), or you can access the Anothercolor variable, because those two environments are its parent execution environment. The scope chain for the above example is:

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 sequential. Each variable can only search the scope chain to the superior to query for variables and function names, that is, first in this role to query the variable or function name, if there is no further up-level scope chain query until the top-level scope. However, no environment can search the scope chain and enter another execution environment.

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

1. Extend the scope chain

The scope chain is extended when the execution stream enters any of the following statements:

Catch block for Try-catch statement

with statement

The two statements add a variable object to the front 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 that contains the declaration of the wrong object being thrown.

As an example:

function BuildUrl () {
  var qs = "Debug=true";
  With (location) {
    var url = href + qs;
  }
  return URL;

The WITH statement receives the location object, so its variable object contains the properties and methods used for the location object, which is added to the front of the scope chain. When the variable href is referenced in the WITH statement (the actual reference is Location.href), it can be found in the current environment variable. When referring to the variable QS, the reference is to the variable defined in BuildUrl (), which is in the function environment variable object. Within the WITH statement, a variable named URL is defined, so that the URL becomes part of the function execution environment and can be returned as the value of the function.

2. No block-level scopes

In JavaScript, enclosed curly braces have no scope of their own. Look at the following code:

if (true) {
  var color = ' Blue ';
}
alert (color);  "Blue"

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

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

Garbage collection

Like Java, JavaScript also has an automatic garbage collection mechanism. The execution environment is responsible for managing the memory used during code execution. When writing a program, you do not need to have a relational memory usage problem, the allocation of required memory, and the recovery of unwanted memory fully automate management. The mechanism of garbage collection is to find the variables that are no longer in use, and then release the memory they occupy. To do this, the garbage collector periodically performs this operation at a fixed time interval (or the scheduled collection time in code execution).

Before making a garbage collection, you must determine whether the resource is useless and mark the unused variables for future memory recovery. The policy used to identify the useless variable usually has two implementations.

1 Mark Purge

The most common method of garbage collection in JavaScript is flag cleanup. When a variable enters the environment, it marks the variable as "entering the environment", and when the variable leaves the environment, it marks the variable as "out of the environment." The garbage collector marks the variables that are used when they are run. It then removes the variables in the environment and the tags of the variables referenced by the variables in the environment. The variables that are tagged after this are considered variables to be deleted, the last garbage collector completes the memory cleanup, destroys tagged values, and reclaims the memory space they occupy.

2. Reference count

Reference counting is the number of times that a trace record is referenced for each value. When a variable is declared and a reference type value is assigned to the variable, the number of references to that value is 1. If the same value is assigned to another variable, the number of references to that value is 1. Conversely, if the variable that contains the reference to that value gets another variable, the reference number of that value is reduced by 1. When the number of references to this variable is 0 o'clock, there is no way to refer to the variable again, so the memory space can be recycled back. When the garbage collector next runs, it reclaims the memory occupied by values that have zero reference times.

One problem with reference counting is that it can cause circular references. For example:

function problem () {
  var obja = new Object ();
  var objb = new Object ();

  Obja.someotherobj = OBJB;
  Objb.someotherobj = Obja;
}

In the example above, Obja and OBJB refer to each other through attributes. After the function completes, the Obja and OBJB will continue to exist, and their reference count will not be 0. This situation causes obja and OBJB to be unable to reclaim memory.

Above this article on javascript: implementation of the environment, scope and garbage collection is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.