Study Notes on JavaScript advanced programming 2-variables, scopes, and memory

Source: Internet
Author: User
Tags getcolor

I. Basic Type value and reference type value

Basic Type Value: Simple data fields stored in the stack memory. The five basic types of values are Undefined, Null, Boolean, Number, and String. They are completely stored in a location in the memory, access them by value.

Reference Type Value: Objects stored in heap memory, that is, the objects stored in the variable are actually a pointer. This Pointer Points to another location in the memory, where the objects are saved. When querying variables of the reference type, read the memory address from the stack first, and then find the value stored in the heap, that is, the reference type is accessed by reference, we operate not on the actual value, but on the object referenced by that value.

Each value stored in the stack memory can access them in sequence, but the value in the stack cannot, because the memory space required by each object is not equal.

1. dynamic attributes

For a value of the reference type, you can add attributes and methods to it, or change or delete its attributes and methods:

var person = new Object();person.name = 'chemdemo';alert(person.name);//chemdemo

Create an object and save it in the person variable to add attributes to the object. If the object is not destroyed or the property is not deleted, the property will always exist.

However, you cannot add attributes or methods to basic types (though this will not cause any errors ):

var person = 'me';person.name = 'chemdemo';alert(person.name);//undefined

2. Copy the variable value

There are also differences between copying basic and reference type values from one variable to another.

Copy the basic type value, create a new value in the stack, and then copy the value to the location allocated for the new variable:

var num1 = 5;var num2 = num1;

After copying, the value in num2 is completely independent from the value in num1. This value is only a copy of 5 in num1. That is, these two variables can be involved in any operation without affecting each other.

When copying a reference type value, the copy of this value is actually a pointer, and this pointer points to an object stored in the heap. After the copy operation is complete, the two variables actually reference the same object. Changing one of the variables will change the other one:

var obj1 = new Object();var obj2 = obj1;obj1.name = 'demo';alert(obj2.name);//demo

3. PASS Parameters

All function parameters in ECMAScript are passed by value (that is, copying the value outside the function to the parameter inside the function is the same as copying the value from one variable to another ).

When passing a basic type value to a parameter, the passed value will be copied to a local variable (that is, a named parameter or an element in the arguments object ); when passing a reference type value to a function, the address in the memory of this value is copied to a local variable. Therefore, the change of this local variable is reflected outside the function.

function addTen(num) {return num + 10;}var count = 20;var result = addTen(count);alert(count);//20alert(result);//30

The addTen () function has a parameter num (local variable). When calling this function, count is passed as a parameter to the function. Its value is 20, therefore, the value 20 is copied to the num parameter for use in the function. In the function, the value of the num parameter is added with 10, but this change does not affect the external variable count (if num is passed by reference, the value of the count variable should also be 30, to reflect the internal modification of the function ).

The passed parameters are objects:

function setName(obj) {obj.name = 'chemdemo';}var person = new Object();setName(person);alert(person.name);//chemdemo

Create an object and save it in the variable person. Then the object is passed to the function and copied to the obj parameter. Within the setName () function, the obj and person variables reference the same object (that is, even if this object is passed by value, obj accesses the same object by reference ), therefore, after adding an attribute to the obj in the function, the person variable outside the function is also reflected.

The following example further demonstrates the function passing by value:

function setName(obj) {obj.name = 'demo';obj = new Object();obj.name = 'chemdemo';}var person = new Object();setName(person);alert(person.name);//demo

If the person is passed by reference, the person will be automatically changed to a new object pointing to its name attribute value "chemdemo. In fact, when you override obj in a function, the reference of this variable is a local object, and this local variable will be destroyed immediately after the function is executed.

Note: ECMAScript function parameters can be considered as local variables.

4. Detection type

To detect the simple data type of a variable, the best tool is to use the typeof operator (if the value of the variable is null or an object, typeof will return "object "):

var s = 'chemdemo';var b = true;var i = 22;var u;var n = null;var o = new Object();alert(typeof s);//stringalert(typeof b);//booleanalert(typeof i);//numberalert(typeof u);//undefinedalert(typeof n);//objectalert(typeof o);//object

When detecting referenced values, the instanceof operator is used:

Alert (person instanceof Object); // is the variable "person" an Object? Alert (colors instanceof Array); // is the variable "person" an Array? Alert (pattern instanceof RegExp); // is the variable person RegExp?

According to the regulations, the values of all reference types are instances of objects (so when detecting a reference type and Object constructor, The instanceof operator always returns true ).

Note: When the instanceof operator detects the basic type value, it always returns false (the basic type is not an object ).

Ii. Execution Environment and scope

Execution EnvironmentDefines other data that variables or functions have access to, and determines their respective actions. Each execution environment has a variable object associated with it. All variables and functions defined in the execution environment are stored in this object.

The global execution environment is the most peripheral execution environment. In a Web browser, the global execution environment is considered a window object. Therefore, all global variables and functions are defined as properties or methods of the window object. After all the code in an execution environment is executed, the environment is destroyed, and the variables and functions stored in the environment are also destroyed (the global variable execution environment is executed until the application exits, such as closing the browser, ).

Every function has its own execution environment. When it is executed in the execution environment, will it create a variable object'sScope chainThe purpose of the scope chain is to ensure orderly access to all variables and functions that have the right to access the execution environment.

The front end of the scope chain is always the variable object in the environment where the code currently executed is located; the next variable object comes from the next inclusion environment, which is extended to the global environment; the variable object in the global execution environment is always the last object in the scope chain.

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 environment. You can access the variable color in the function because it can be found in the scope chain.

Variables defined in the local scope chain can be used with global variables in the local environment:

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, anotherColorswapColors () ;}cnahgecolor (); // here you cannot access anotherColor and tempColor, however, you can access coloralert ("Color is now" + color );

The preceding Code involves three execution environments: Global Environment, changeColor () local environment, and swapColor () local environment. In the global environment, there is a variable color and a function changeColor (); in the local environment of changeColor (), there is a variable named anotherColor and a function named swapColor, however, it can access the global variable color ...... and so on.

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 connections between these environments are linear and ordered. Each environment can search for the variable and function name in the scope chain, however, no environment can enter another execution environment by searching down the scope chain.

For the above example, swapColor () Scope chain contains three objects (changeColor () Scope chain contains two objects): swapColor () variable object, changeColor () the local environment of swapColor () First searches for the variable name and function in its own variable object. If it cannot be found, it searches for the chain of the upper-level scope.

Note: function parameters are also treated as variables, so the 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:

  • 1) catch Block of the try-catch statement
  • 2) with statement

These two statements Add a variable object at the front end of the scope chain. For with, its variable object contains all the attributes of the specified object and the variable declaration made by the method; for catch, its variable object contains the declaration of the thrown error object. These Scalar objects are read-only. Therefore, variables declared in the with and catch statements are added to the variable objects in the execution environment.

Example:

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

With receives the location object, so its variable object contains all the properties and methods of the location object, and this variable object is added to the front end of the scope chain. When the href variable (actually location. href) is referenced in with, it can be found in the variable object of the current execution environment (buildUrl.

Note: In IE, the error object captured in the catch statement will be added to the variable object in the execution environment, that is, the error object can be accessed even outside the catch.

2. No block-level scope

Example:

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

In C, C ++, or Java, color is destroyed after the if statement is executed, but in JavaScript, the variable declaration in if adds the variable to the current execution environment (Global Environment.

For example:

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

The variables created by the for statement also exist in the execution environment outside the loop after the for statement is executed.

1) declarative Variables

When you declare a variable using var, the variable is automatically added to the nearest available environment. For a function, the latest environment is the local variable of the function; for a with statement, it is also the function environment. If the variable is initialized without being declared, it is automatically added to the global variable.

 

Function add (num1, num2) {var sum = num1 + num2; return sum;} var result = add (10, 10); alert (result ); // 20 alert (sum); // error, because sum is not a valid variable

If the keyword var in the add function is omitted, alert (sum) outputs 20.

Note: We recommend that you declare the variable before initializing it.

2) query identifier

When an identifier is referenced for reading or writing in an environment, you must search to determine what the identifier actually represents. The search process starts from the front end of the scope chain and goes up to query the identifier that matches the given name until it is found (if it is not found in the global environment, it means the variable is not declared ).

Example:

var color = "blue";function getColor() {return color;}alert(getColor());  //blue

To determine the value of the variable color, first search for the variable object of getColor (), and find whether it contains the identifier named color. If it is not found, the search will continue to the next variable object, then, the variable identifier named color is found.

The modification code is as follows:

var color = "blue";function getColor() {var color = "red";return color;}alert(getColor());  //red

During the search process, if a definition of a local variable exists, the search is automatically stopped (that is, if a required identifier exists in the local environment, the same name identifier in the parent environment is not used ).

Note: Obviously, local variables are faster than global variables because you do not need to search for the scope chain.

Iii. Garbage Collection

1. mark and clear

The most common method of garbage collection in JavaScript is tag clearing. The idea of this algorithm is to mark unused values and recycle their memory. When a variable enters the environment (such as a variable in a function), it is marked as "entering the environment". When the variable leaves the environment, it is marked as "leaving the environment ", finally, the garbage collector clears the memory.

2. Reference count

The trace records the number of times each value is referenced. When the number of references is 0, the occupied memory space is reclaimed.

The reference count may have the "loop reference" problem:

function problem() {var objectA = new Object();var objectB = new Object();objectA.someOtherObject = objectB;objectB.anotherObject = objectA;}

ObjectA and objectB use their respective attributes to reference each other. The number of times the two objects are referenced is 2. After the function is executed, objectA and objectB will continue to exist, and the number of times they are referenced cannot be 0.

For example, in IE, objects in BOM and DOM are implemented in the form of COM objects, and the garbage collection mechanism of COM objects is to reference the counting policy. Therefore, the js engine using IE is implemented by clearing the tag policy, but the COM Object accessed by js is still based on the reference counting policy.

var element = document.getElementById("element");var myObject = new Object();myObject.element = element;element.someObject = myObject;

A circular reference is created between a DOM element and a native JavaScript Object (myObject.

You can use the following code to remove circular references:

myObject.element = null;element.someObject = null;

3. Performance problems

Mainly for browsers earlier than IE7.

4. Manage memory

Make sure that the minimum memory usage can improve the page performance. The best way to optimize memory usage is to save only necessary data for the code being executed. Once the data is no longer useful, it is best to set it to null to release its reference. This method is applicable to the attributes of most global variables and global objects. Local variables are automatically removed when they leave the implementation environment.

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.