Total four (2) of JavaScript advanced programming

Source: Internet
Author: User

Introduction: This section summarizes the execution environment and scope, as well as the memory and garbage mechanisms of JavaScript.

execution Environment: The execution environment (or directly called the environment) is the most important concept in JavaScript, and the execution environment defines the other data that variables or functions have 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 saved in this object. Although the code we write does not have access to this object, the parser uses it in the background when it processes the data.

The global execution environment is the outermost environment in which the global execution environment is considered a Window object, so you can also assume that all global variables and functions are created as properties and methods of the Window object. When all code in an execution environment is executed, the environment is destroyed, and all variables and function definitions stored therein are destroyed (the global execution environment is not destroyed until the application exits-for example, when the Web page or browser is closed).

Scope Chain: Contemporary code when executed in an environment, creates a scope chain for the variable object, and the role of the scope chain is to ensure an orderly access to all the variables and functions that the execution environment is authorized to access. The front end of a scope chain is always a variable object of 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, which does not exist in the global environment. The next variable object in the scope chain comes from the containing (external) environment, and the next object comes from the next containing environment, which continues to the global environment, and the variable object of the global execution environment is always the last object in the scope chain. This is a bit of a detour, we look directly at the example:

                            

var color= "Blue";
function ChangeColor () {
var anothercolor= "Red";
function Swapcolors () {
var Tempcolor=anothercolor;
Anothercolor =color;
Color =tempcolor;
Here you can access the color Anothercolor and Tempcolor
}
Here you can access color and anothercolor but cannot access Tempcolor
Swapcolors ();
}
Only color can be accessed here
ChangeColor ();

The above involves three execution environments, the global variable environment, the local variable environment of ChangeColor (), and the local variable environment of swapcolors (). It can be seen from the example above. The scope chain for this execution is internal to external, that is, the "use the next variable object in the domain chain from the containing (external) environment, and then the next object from the next containment environment, which continues to the global environment ." In this way, the intrinsic function can use variables of the external function as well as global variables, but conversely, we cannot directly access variables in the inner function outside. After that there was also a closure (which we'll summarize later).

extend the scope chain: when the execution function flows into any of the following statements, the scope chain is lengthened:1, the CATCH Block 2 for the Try-catch statement, and the WITH statement.

Give me a chestnut:

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

                                    

Here with receives the location object, so its variable contains all the properties and methods of the Location object, and this object is added to the scope front end. So here we can refer to the variable QS. As for the inside of the WITH statement, a URL variable is defined, so the URL becomes part of the function execution environment, so it can be returned as the value of the function.

PS (in IE8 and its previous versions, Cath's error objects are added to the execution environment rather than in the catch environment, so there is a case where the Error object can be accessed outside of the catch in IE8 and its previous versions, and this problem is IE9 and repaired).

Garbage collection mechanism:

JavaScript has a garbage collection mechanism, which means that the execution environment is responsible for managing the memory used by the code execution process. The principle of this garbage collection mechanism is simple: identify the unused variables and then release the resources that they occupy. To do this, the garbage collector performs this periodically at fixed intervals (or during the scheduled collection time in code execution).

the normal life cycle of local variables: local variables exist only during the execution of a function, and in this process, the local variables are allocated the appropriate space on the stack (or heap) in order to store its value. These variables are then used in the function until the function ends, at which point there is no need for local variables to be present, so that their memory can be freed. In this case it is easy to determine if there is a need for a variable, but not all cases are so easily concluded. The garbage collector must keep track of which variable is useful and which is useless. Label the variables that are not useful so that their resources are released later. The policy used to identify the useless variable may vary depending on the time, but it is implemented in the browser in two ways:

1, Mark clear: This is the most common way of garbage collection JavaScript, when the variable into the execution environment, such as declaring a variable in the function, the garbage collector labeled "into the environment" when the variable leaves the environment (function execution end) mark it as "leave the environment." There are many ways to tag, such as the reversal of a particular bit, the maintenance of a list, and so on, which are not important,

What strategy to use, in principle, is not able to release the memory of the variables that enter the environment, they may be called at any time.

The garbage collector will tag all variables stored in memory at run time, then remove the variables in the environment and the variables referenced by the variables in the environment (closures), after which there are still tags to be deleted, because variables in the environment are inaccessible to these variables. The garbage collector then encounters the space occupied by these tagged variable machines.

Most browsers use this method of garbage collection, the difference is how to mark and garbage collection interval, only the low version of IE, as expected, is IE ...

2. Reference count: Another less common garbage collection strategy is the reference count. The meaning of the reference count is the number of times each value is referenced by the tracking record. When a variable is declared and a reference type is assigned to the variable, the number of references to that value is 1. Conversely, if a variable that contains a reference to this value has another value, the number of references to this value is reduced by 1. When this number of citations becomes 0

, it means that there is no way to access the value again, so it can take up the memory space it occupies. In this way, the next time the garbage collector runs, it frees the memory of those values that have a reference count of 0.

Reference counting is easy to understand, but when used, there is a problem with circular referencing:

Function Pro () {

var a=new Object ();

var b=new Object ();

A.obj=b;

B.obj=a;

In this function, A and B are referenced by each other by their respective properties. That is, the number of references to both is 2. This is embarrassing, when the function is finished, the two references are not 0, then the way to reference the count is not. If this method is executed multiple times, the variables inside will accumulate, which is not the result we want to see.

    

We know that some of the objects in IE are not native JavaScript objects. For example, the object in its BOM and Dom is to use C + + with COM (Component object
Model, the Component Object) object, and the garbage collector of the COM object is the policy that uses the reference count. Therefore, even though the JavaScript engine of IE is implemented with a policy of tag cleanup, the COM objects that JavaScript accesses are still based on the policy of reference counting. To be blunt, as long as the COM object is involved in IE, there will be a circular reference problem. Take a look at the following simple example:

var element = document.getElementById ("Some_element"), var myObj =new Object (), myobj.element = element; Element.someobject = MYOBJ;

In this example, a circular reference is established between a DOM element and a native JavaScript object (MYOBJ). Where the variable myobj has a property named element pointing to Element, and the variable element has a property named Someobject that refers to MyObj. Because of the circular reference, even if the DOM in the example is removed from the page, memory is never recycled.

However, the above problems are not unresolved, we can manually cut off their circular references.

Myobj.element = Null;element.someobject =null;

This code can solve the problem of circular reference, but also prevent the problem of memory leaks.

To solve these problems, however, IE9 the BOM and Dom objects into real JavaScript objects. This avoids the problems caused by the coexistence of two garbage collection algorithms. The problem of memory leaks is also prevented.

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------

The end of this chapter. Next Chapter Trailer:

The reference type.

We know that there are two types of JavaScript, data types and reference types. The previous summary has allowed us to understand the underlying data types and then let's go into the world of reference types.

Total four (2) of JavaScript advanced programming

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.