JavaScript Advanced Programming Learning (c) variables, scopes, and memory issues

Source: Internet
Author: User
Tags variable scope

This is mainly about variables, scopes, and memory issues.

Any programming language involves these three.

variables, such as global variables, local variables, scopes, and global scopes and method scopes, memory problems, involve a garbage collection problem in Java, and because the JVM is involved in Java, it is possible to automate garbage collection and memory allocation without the need for manual.

One, variable

Each variable has its type, data type. In Java, the basic data types and reference data types, JS is the same.

Interview question: What are the basic data types of Java, and what are their bytes? What are reference types?

The Java base data types are int (4), float (4), double (8), char (2), Boolean (1), Long (8), Byte (2), short (2)

Reference types, such as String or object, enumeration, and so on, can also be answered to say that, in addition to the basic data types described above, they are reference data types.

Out of the question, let's go to the following:

(1) What are the basic data types of JS?

Yesterday's basic concept is said, but today is the system says,

Basic data types are string,number,null,boolean,undefined

Reference data types are Object,array, respectively

A primitive type value refers to a simple data segment, whereas a reference type value refers to an object that may consist of multiple values. When assigning a value to a variable, the parser must determine whether the value is a base type value or a reference type.

The value of a reference type is an object that is saved in memory. Unlike other languages, JavaScript does not allow direct access to in-memory locations, which means that the object's memory space cannot be manipulated directly. When you manipulate an object, you are actually manipulating the object's reference rather than the actual object. To do this, the value of the reference type is accessed by reference.

The above code creates an object and saves it in the variable person, however we add a Name property to the object and assign the string "Hello" to the property. Immediately after that, we access the property through the alert function, and if the property is not destroyed or is not deleted, it will persist.

Note that you cannot add attributes to the base data type, although this does not cause the error to run normally, as shown in:

<HTML><Head><Script>var Person= "Hello";p Erson.name=" World"; alert (person.name)//will result in a value of undefined</Script></Head><Body></Body></HTML>

(2) About copying variable values

var num1=5;var num2=num1;

Although the values of the two variables are the same, they are completely independent of the two variables.

When a value of a reference type is copied from one variable to another, the value stored in the variable object is also copied into the space allocated for the new variable. The difference is that a copy of this value is actually a pointer to an object stored in the heap. When the copy operation is finished, two variables will actually refer to the same object. Therefore, changing one of the variables will affect the other variable.

The code shown:

<script>

var obj1 = new Object ();
Obj1.name= "Hello";
var obj2 = obj1;
Alert (Obj2.name)

</script>
<body>
</body>

(3) Transfer parameters

<HTML><Head><Script>functionAdd (num) {num+=Ten;returnnum;}varCount= -;varresult=Add (count), alert (count) alert (result)</Script></Head><Body></Body></HTML>

Here the function add () has a parameter num, and the argument is actually a local variable of the function. When this function is called, the variable count is passed as a parameter to the function, and the value of the variable is 20. The value 20 is then copied to the parameter num for use in Add (). Inside the function, the value of the parameter num is added to 10, but this change does not affect the count variable outside the function. Parameter num is not acquainted with the variable count, they simply have the same value. If NUM is passed by reference, then the value of the variable count is also changed to 30, which reflects the changes inside the function. Of course, using basic types such as numeric values to illustrate that passing parameters by value is simple, but if you use objects, the problem is not very well understood.

(4) Detection type

The typeof operator is most effective in detecting the data type of a variable, but only for the base data type and not for the reference data type.

You can use the instanceof operator for reference data types

Alert (person instanceof Object); is the variable person an Object? Alert (colors instanceof Array);  is the variable colors an Array? Alert (pattern instanceof REGEXP);  

Attention:

When you use the TypeOf operator to detect a function, the operator returns "function". When using typeof to detect regular expressions in Safari 5 and previous versions and in Chrome 7 and earlier, this operator also returns "function" for canonical reasons. ECMA-262 specifies that any object that implements the [call] method internally should return "function" when the typeof operation is applied. Because the regular expression in the above browsers also implements this method, applying typeof to the regular expression returns "function". In IE and Firefox, applying typeof to Regular Expressions returns "Object".

II. implementation Environment and scope

The execution environment (execution context, which is sometimes referred to as "environment" for simplicity) is one of the most important concepts in JavaScript. The execution environment defines the other data that a variable or function has access to, and determines their respective behavior. Each execution environment has a variable object associated with it (variable object), and all variables and functions defined in the environment are stored in the 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 one of the outermost execution environments. Depending on the hosting environment where the ECMAScript implementation resides, the objects that represent the execution environment are different. In a Web browser, the global execution environment is considered a Window object, so all global variables and functions are created as properties and methods of the Window object. After 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). Each function has its own execution environment. When the execution flow enters a function, the environment of the function is pushed into an environment stack. After the function executes, the stack pops up its environment and returns control to the previous execution environment. The execution flow in the ECMAScript program is controlled by this convenient mechanism. When code executes in an environment, a scope chain of variable objects is created (scope chain). The purpose of a scope chain is to ensure an orderly access to all variables and functions that the execution environment has access to. The front end of the scope chain, which is always the variable object for the environment in which the code is currently executing. If the environment is a function, its active object (activation object) is used as the variable object. The active object initially contains only one variable, the arguments object (this object does not exist in the global environment). The next variable object in the scope chain comes from the containing (external) environment, and the next variable object comes from the next containment environment. In this way, it continues to the global execution environment; The variable object of the global execution environment is always the last object in the scope chain. Identifier parsing is the process of searching identifiers one level at a scope chain. The search process always starts at the front end of the scope chain, and then goes backward backwards until the identifier is found (if an identifier is not found, this usually results in an error).

Example code:

<HTML><Head><Script>varColor= "Blue"; functionChangeColor () {if(Color=== "Blue") {color= "Red"; } Else{color= "Blue";  }} changecolor (); Alert ("Color is now" +color); </Script></Head><Body></Body></HTML>

The following code covers a total of 3 execution environments: The global environment, the local environment of the ChangeColor (), and the local environment of the swapcolors (). There is a variable color and a function changecolor () in the global environment. The local Environment of ChangeColor () has a variable named Anothercolor and a function named Swapcolors (), but it can also access the variable color in the global environment. The local Environment of Swapcolors () has a variable tempcolor, which can only be accessed in this environment. Local environments, whether global or ChangeColor (), do not have access to tempcolor. However, within swapcolors (), you can access all the variables in the other two environments, because those two environments are its parent execution environment.

Example:

<HTML><MetaCharSet= "Utf-8"><Head><Script>varColor= "Blue"; functionChangeColor () {varAnothercolor= "Red"; functionswapcolors () {varTempcolor=Anothercolor; Anothercolor=color; Color=Tempcolor; //Here you can access color, Anothercolor, and Tempcolor        }      //you can access color and anothercolor here, but you cannot access Tempcolorswapcolors (); }  //only color can be accessed hereChangeColor ();</Script></Head><Body></Body></HTML>

Third, garbage collector

JavaScript has an automatic garbage collection mechanism, which means that the execution environment is responsible for managing the memory used during code execution. In languages such as C and C + +, a basic task for developers is to manually track memory usage, which is a source of many problems. When writing JavaScript programs, developers no longer care about memory usage issues, the allocation of required memory, and the recycling of useless memory are fully automated management. The rationale for this garbage collection mechanism is simple: identify 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 a predetermined collection time in code execution). Let's examine the normal life cycle of local variables in the function. Local variables exist only during the execution of a function. In this process, the local variables are allocated the appropriate space on the stack (or heap) memory to store their values. These variables are then used in the function until the function execution is finished. At this point, there is no need for local variables to exist, so they can be freed up for future use. In this case, it is easy to determine whether the variable is still necessary, but not all the circumstances are so easy to reach a conclusion. The garbage collector must keep track of which variables are useful and which ones are useless, marking variables that are no longer useful for future recall of their occupied memory. The policy used to identify the useless variable may vary by implementation, but there are typically two policies that are specific to the implementation in a browser.

(1) Mark Clear

The most common method of garbage collection in JavaScript is tag Cleanup (mark-and-sweep). When a variable enters the environment (for example, when declaring a variable in a function), the variable is marked as "entering the environment." Logically, you can never release a change in the environment
As long as the execution stream enters the appropriate environment, it may be used. When the variable leaves the environment, it is marked as "out of the environment." You can use any way to tag variables. For example, you can record when a variable enters the environment by flipping a particular bit, or use a "go to environment" variable list and a "Leave environment" variable list to track which variable has changed. In the final analysis, how to tag variables is not important, but the key is to adopt any strategy. The garbage collector will tag all variables stored in memory at run time (of course, you can use any markup method). It then removes the variables in the environment and the tags of the variables referenced by the variables in the environment. Variables that are tagged later will be considered as variables to be deleted because variables in the environment are inaccessible to those variables. Finally, the garbage collector completes the memory cleanup work, destroys those tagged values, and reclaims the memory space that they occupy.

(2) Reference count

Another less common garbage collection strategy is called reference counting (reference counting). 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 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 added by 1. Conversely, if a variable that contains a reference to this value has another value, the number of references to the value is reduced by 1. When the number of references to this value becomes 0 o'clock, it means that there is no way to access the value again, so that it can reclaim the memory space it occupies. That way, when the garbage collector runs again next time, it frees the memory used by those values that have a zero reference count.

Summary:

Disclaimer: The article has some conceptual relevance, and I cite the book, "JavaScript Advanced programming," since it is a systematic study that involves some concepts. Although the concept is dull, but do not know the point is still not good.

Personal experience: As a web developer, write foreground also write backstage, foreground words, in addition to variable scope and function execution order or parameter pass these use more, also consider more, like memory management this, contact very little. Garbage collection, background Java has its own garbage collection mechanism, without our Java developers to consider, JS memory management, in my opinion I really do not know where to use, for JS garbage collection and memory management knowledge I hardly know there is such a thing, read this book, Just know that the original JS and Java has its own garbage collection mechanism, do not need us to consider too many people. This system learning is also known under.

I personally in the follow-up development, JS Performance is also a special concern, for this I refer to many csdn or blog park and related books on the performance optimization of the site, especially about books, I personally uploaded a folder, which contains the site performance optimization of 14 recommendations. We can refer to, although not so careful, but I think it should be more comprehensive. The 14 recommendations read the book "High-performance website building Guide". The book Web Developer, I think it is necessary to read.

This summary of knowledge can be divided into the following:

JavaScript variables can be used to hold two types of values: primitive type values and reference type values.

The value of the base type is derived from the following 5 basic data types: Undefined, Null, Boolean, number, and String.

Basic type values and reference type values have the following characteristics:

? The base type value occupies a fixed amount of space in memory and is therefore stored in the stack memory;

? Copying a base type value from one variable to another creates a copy of the value;

? The value of a reference type is an object that is stored in heap memory;

? A variable that contains a reference type value actually contains not the object itself, but a pointer to that object;

? Copying the value of a reference type from one variable to another is actually a pointer, so two variables end up pointing to the same object;

? Determine which base type a value can use the TypeOf operator, and determine which reference type can use the instanceof operator;

All variables, both basic and reference, exist in an execution environment (also known as a scope), which determines the life cycle of the variable and which part of the code can access the variables. Here are a few summaries of the implementation environment:

? The execution environment has a global execution environment (also known as the Global Environment) and the function execution environment points;

? Each time you enter a new execution environment, you create a scope chain that is used to search for variables and functions;

? The local environment of a function not only has access to variables in the scope of the function, but also has access to its containing (parent) environment, and even to the global environment;

? The global environment can only access variables and functions defined in the global environment, and cannot directly access any data in the local environment;

? The execution environment of a variable helps determine when memory should be freed.

JavaScript is a programming language with an automatic garbage collection mechanism, and developers don't have to worry about memory allocation and recycling issues. You can summarize the garbage collection routines for JavaScript as follows.

? The values that leave the scope are automatically marked as recyclable and therefore will be deleted during garbage collection.

? "Tag Cleanup" is currently the mainstream garbage collection algorithm, the idea is to add tags to the currently unused values, and then reclaim their memory.

? Another garbage collection algorithm is a "reference count", the idea of which is to track the number of times all values are referenced. The JavaScript engine is no longer using this algorithm, but this algorithm can still cause problems when accessing non-native JavaScript objects such as DOM elements in IE.

? The reference count algorithm causes problems when there is a circular reference phenomenon in your code.

? Removing a reference to a variable not only helps eliminate circular references, but also benefits garbage collection. To ensure that memory is effectively reclaimed, you should release the references to the global objects, global object properties, and circular reference variables that are no longer in use in a timely manner.

JavaScript Advanced Programming Learning (c) variables, scopes, and memory issues

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.