JavaScript variable scope and memory issues (JS Advanced programming Summary)

Source: Internet
Author: User
Tags variable scope

1, variable

are ECMAScript and JavaScript equivalent? Personal opinion is negative. My understanding is that ECMAScript is a complete set of standards or protocols, and JavaScript is a set of scripting languages implemented on a browser. In other words, ECMAScript is the parent standard of JavaScript. JavaScript is a concrete implementation of ECMAScript. All ECMAScript defined data types or language features are actually in the form of pseudo-code. Of course, if you can, ECMAScript can also have a server implementation, single-chip implementation (not necessarily appropriate). If ECMAScript is an interface, it seems to be quite an image.

There are five basic data types for JavaScript (raw data type): Undefined, Null, Boolean, number, String. The basic data type refers to the simple data segments that are stored in the stack memory . Why save to Stack memory? Because the size of the base data type value is actually fixed. In other words, the data is completely stored in a single place in memory. Because of this feature, access to the base data type is actually accessed by value, because we are actually manipulating the saved values.

Another data type in JavaScript is called a reference type value. Unlike the base data type, the reference data inner type is an object that is stored in heap memory . It means that the variable is actually just a pointer to another location in memory where the object is saved. And this variable pointer is stored in the stack memory. Similarly, access to this type of value actually accesses a pointer to an object, thereby indirectly accessing the data object.

Let's talk about the variable assignment process:

var a=1; var b=a;a+ +; alert (a); // 2 // 1

it's obvious. The assignment operation of the base data type is actually independent!

Let's look at another example of a reference type:

var  New String ("Hello,hz"); var newstr = str;str.name= "Huazi"; alert (str.name);            // Huazi     alert (newstr.name);   // Huazi

In fact, str and NEWSTR are pointing to the same heap of memory. Of course, both STR and NEWSTR are pointer variables in the stack memory.

2. function parameter Problems

There are two scenarios for the function-transfer of JavaScript. If the basic data type is passed a reference, then the object or reference is the passed reference. Of course you can also understand that all function parameters are value passing, but the value needs to be divided into two situations. values, pointers. ,

function Test (data) {       return data++;} var num = ten; var res = Test (num), alert (num);     // Tenalert (res);   //  One

What does that mean? value passing is a value, and there is no correlation.

var New Object ("Hello,hz"); Console.log (obj.name); // Undefiend var function (args) {    args.name= "Huazi"    return  args;} var newObj = fun1 (obj); Console.log (newobj.name); // HuaziConsole.log (obj.name); // Huazi

Pass the reference.

3.JavaScript execution Environment and scope

to understand the scope of JavaScript you have to talk about the JavaScript execution environment first. Execution Environment is one of the more important concepts in JavaScript. The execution environment defines an environment variable object that is associated with the environment. Of course, you can't manipulate this object. But it will be used when the browser parses the script. Functions and variables defined in the execution environment are stored in this variable object.

The global execution environment is the outermost execution environment. Depending on the host environment of the ECMAScript, the objects that represent the environment are also different. For JavaScript, the host is a browser. That is, the global execution environment is a window object. When all the code in an environment is pointed , the environment will be destroyed. However, it is important to note that the Global object window is not destroyed. The Window object is destroyed only when the Web page or browser is closed.

Each function creates its own execution environment at execution time, and when the execution flow enters a function, the environment of the function is pushed into an environment stack . Execute, out stack. Return control to the previous execution environment. This is how the ECMAScript execution flow is controlled by this mechanism.

The scope chain is made up of variable objects, and the purpose of the scope chain is clear. is to ensure an orderly access to all variables and functions that the environment has access to. The front end of the scope is always a variable object for the code that is currently running. It is important to note that if a function is executed at this point, it The active object is used as a variable object. The active object initially contains only one variable, the Parameter object arguments. The next variable object in the scope chain is its parent containing variable object. The last variable object of a variable scope chain is naturally a global variable object.

The judgment of variable accessibility is based on the scope chain to find the identifier, followed by backtracking. Note that this is the problem of precedence in that it is backtracking in turn. The closer the variable object is used, the more likely it will be found and called by the first. If you do not find a natural error.

Special Try-catch and with statements extend the scope chain. Because with (?) and catch (Error),?, and error are read-only, so they are added to the variable object in the execution environment.

JavaScript is not a block-level scope. You may need to be aware of the for (Var i=0; ...) when writing a For loop. After this is done, I still have a value after executing the FOR statement and will not be released immediately.

4, garbage collection memory management

JavaScript, like Java, has an automatic recycling mechanism, which means that the execution environment is responsible for managing the memory used during code execution. and the C + + flow is to developers to manually track the use of memory, which is the cause of many problems. The garbage collection mechanism of JavaScript is simple: Identify variables that are no longer in use, and then release the space they occupy. To do this, the garbage collector periodically performs this operation at regular intervals. (different browsers have different definitions for time intervals.)

Recycling policy:

1, Mark Clear

The most common garbage collection method for JavaScript is tag cleanup . When the variable enters the environment, it marks the variable as entering the environment state. When a variable leaves the environment, it marks it as leaving the environment. You can use any method of marking, such as flipping a bit in a particular position to mark it, or maintaining a list of variables to track the tag.

When the garbage collector runs, it returns a tag to No table, and then cancels out the variable tags that are not in the environment. A variable that is still tagged after this is considered a variable to be deleted. The reason is that the environment has no access to them. Finally, the garbage collector's memory is cleared.

2, reference count

Reference counting is a policy that has been eliminated, but in some versions of IE, the memory management of BOM and DOM elements still uses reference counting. Because these objects are not JavaScript native, they are COM implementations that use C + +. COM is implemented by using reference counting. So it is necessary to understand. Avoid bugs caused by circular references.

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 value of a reference type is assigned to the variable, The number of references to this value is added by 1. If the same value is assigned to another value, then the value is quoted a further 1. Conversely, if a variable that contains a reference to this value is obtained with a new value, the number of references to the value is reduced by 1. When a value is referred to as 0, there is no way to reference it. Garbage collection.

For security and avoidance of unexpected occurrences, it is recommended that you de-reference the relationship yourself after using the full local variables, global object properties, and circular references . Obj=null; It is important to note that this practice does not immediately reclaim memory. Just leave it out of the execution environment (it must be marked and the next collector is afraid to destroy it).

JavaScript variable scope and memory issues (JS Advanced programming Summary)

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.