Section 106th, JavaScript variable scope and memory

Source: Internet
Author: User
Tags variable scope

JavaScript variable scope and memory

Learning Essentials:

1. Variables and scopes

2. Memory issues

JavaScript variables differ greatly from those of other languages. A JavaScript variable is a loosely-typed (non-mandatory type) nature that determines just one name that is used to hold a particular value at a particular time. Because there is no rule that defines what data type values A variable must hold, the value of the variable and its data type can change over the lifetime of the script.

A. variables and scopes

1. Values for basic types and reference types

The ECMAScript variable may contain values for two different data types : The base type value and the reference type value . Primitive Type values refer to simple data segments that are stored in the stack's memory, meaning that this value is completely stored in a single location in memory. The reference type value refers to the object that is stored in the heap memory, meaning that the variable is actually just a pointer to another location in memory where the object is saved.

When assigning a value to a variable, the parser must determine whether the value is a base type value or a reference type value. There are several basic types of values: Undefined, Null, Boolean, number, and string. These types occupy a fixed size of space in memory, and their values are stored in the stack space, which we access by value.

PS: In some languages, strings are represented as objects and are therefore considered reference types. ECMAScript to abandon this tradition.

If you assign a value of a reference type, you must allocate space for the value in heap memory. Because the size of this value is not fixed, they cannot be saved to the stack memory. But the memory address size is fixed, so memory addresses can be saved in the stack memory. Thus, when querying a variable of a reference type, the memory address is read from the stack and then the value in the heap is found through the address. For this, we call it access by reference.

2 Dynamic Properties

You define a primitive type value and a reference type value in a similar way: Create a variable and assign a value to the variable. However, when this value is saved to a variable, the actions that can be performed on the different types of values are quite distinct.

Reference types can append data

var New Object ();                        // Create reference type box.name = ' Lee ';                            // added a property alert (box.name);                            // Output

If the value of the base type is added to the data, there will be a problem.

var box = ' Lee ';                            // Create a basic type box.age =;                                // Add attribute alert (box.age) to the base type;                                // undefined    

3. Copying variable values

In the context of variable copying, the basic type and reference type are different. The base type replicates the value itself, and the reference type replicates the address.

Basic type

var box = ' Lee ';                            // Generate a box ' Lee ' in stack memory var box2 = box;                            // regenerate the stack memory into a box2 ' Lee '

Box2 is a copy of the Box1, but as can be seen from the diagram, it is completely independent. That is, two variables do not affect each other.

Reference type

var New Object ();                        // Create a reference type box.name = ' Lee ';                            // Add a property var box2 = box;                            // Assign the reference address to Box2

In reference types, Box2 is actually box because they point to the same object. If the Name property in this object is modified, the values of the box2.name and box.name outputs are modified accordingly.

4. Passing parameters

The arguments for all functions in ECMAScript are passed by value, meaning that the arguments are not passed by reference, although the variables have a base type and a reference type.

function box (num) {                        // passed by value, the passed parameter is the basic type    num + = ten;                            // num Here is a local variable, and the global is invalid    return num;} var num =; var result = box (num), alert (result);                             // alert (num);                                //  -

PS: In the above code, the passed parameter is a basic type of value. Num in the function is a local variable with no connection to num outside.

An example of a parameter as a reference type is given below.

 the function box (obj) {                            // is passed by value, the passed parameter is a reference type, and the definition functions    obj.name = ' Lee ';} var New Object ();                      // define a variable, the value is the Object box (p);                                    //  alert (p.name);

PS: If there is a pass by reference, then the variable in the function will be a global variable and can be accessed externally. For example, in PHP, you must precede the parameters with the & symbol to pass by reference. ECMAScript does not have these, it can only be local variables.

PS: So passing and passing a reference type by reference is two different concepts.

function box (obj) {    = ' Lee ';     var New Object ();                    // an Object    is created inside the function Obj.name = ' Mr. ';                        // did not replace the original obj}

Finally, we conclude that the parameters of the ECMAScript function will be local variables, that is, not passed by reference.

5. Detection type

To detect the type of a variable, we can distinguish it by the typeof operator. Such as:

var box = ' Lee '; alert (typeof box);                            // string

Although the typeof operator is very useful when checking the basic data type, it is less useful when detecting reference types. Often, we don't want to know if it's an object, but rather what kind of object it is. Because arrays are also object,null and object, and so on.

At this point we should use the instanceof operator to view.

The instanceof operator, which determines whether an object's data is the specified type, returns a Boolean value

varbox = [A.];alert (BoxinstanceofArray);//whether it is an arrayvarBox2 ={};alert (Box2instanceofObject);//whether it is an objectvarBox3 =/g/; alert (Box3instanceofREGEXP);//whether it is a regular expressionvarBox4 =NewString (' Lee '); alert (Box4instanceofString);//whether it is a string object

PS: When you use instanceof to check the value of a base type, it returns false.

6. Execution Environment and scope

The execution environment 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.

The global execution environment is the outermost execution environment. In a Web browser, the global execution environment is considered a Window object. All global variables and functions are therefore created as properties and methods of the Window object.

Global variables can be accessed in functions

var box = ' Blue ';                            // declaring a global variable function Setbox () {    alert (box);                             // Global variables can be accessed in functions }setbox ();                                     // Execute function

Global variables and functions are properties and methods of the Window object.

var box = ' Blue '; function Setbox () {    alert (window.box);                         // The global variable is the property of window }window.setbox ();                             // the method of the global function that is window

PS: When all the code in the execution environment is executed, the environment is destroyed, and all the variables and function definitions stored therein are destroyed. If it is a global environment, it needs to be executed, or the webpage will be closed before it is destroyed.

PS: Each execution environment has a variable object associated with it, just as the global window can invoke variables and properties. The local environment also has a variable object like window, and all variables and functions defined in the environment are stored in the object. (We cannot access this variable object, but the parser handles the data when it is used in the background)

the variables in the function can only be used in the function body, the variables in the local scope of the function replace the global variables, but the scope is limited to the local environment within the function body.

var box = ' Blue '; function Setbox () {    var box = ' red ';                        // This is a local variable, and I don't know it.     alert (box);} Setbox (); alert (box);

By passing a parameter, you can replace a local variable in the function body, but the scope is limited to the local environment within the function body.

var box = ' Blue '; function setbox (box) {                        // by using the parameter, replace the global variable     alert (box);} Setbox (' red '); alert (box);

The function body also contains functions, only this function can access the inner layer of the function.

var box = ' Blue '; function Setbox () {    function  setcolor () {        var b = ' orange ';        alert (box);        alert (b);    }    SetColor ();                             // setcolor () execution Environment within Setbox () }setbox ();

PS: Each function is invoked to create its own execution environment. When this function is executed, the environment of the function is pushed to the environment stack to execute, and then pops up (exits) in the environment stack, giving control to the execution environment at the upper level.

PS: When the code is executed in an environment, it forms something called a chain of scopes. Its purpose is to ensure orderly access to variables and functions that have access in the execution environment. The front end of the scope chain is the variable object that executes the environment.

7. No block-level scope

Block-level scopes represent blocks of code, such as if statements, that have braces closed, so that conditional judgments are supported to define variables.

If statement code block does not have a local scope

if (true) {                                    //If statement code block has no local scope    var box = ' Lee ';} alert (box);

The same is true for a For loop statement

 for (var i = 0; i <; i + +) {                    // no local scope    var box = ' Lee ';} alert (i); alert (box);

The difference of the VAR keyword in the function

function box (NUM1, num2) {    var sum = num1 + num2;                // If you remove Var, it's a global variable.    return sum;} Alert (Box (10,10)); alert (sum);                                 // Error

PS: It is not recommended to initialize variables without using Var, because this method can cause a variety of unexpected occurrences. Therefore, you must add var when initializing variables.

A generic deterministic variable is a search to determine what the identifier actually represents.

var box = ' Blue '; function Getbox () {    return box;                            // represents the global box}                                        // If you add the function body plus var box = ' Red 'alert (Getbox ());                        // then the last return value is red .

PS: In variable queries, accessing local variables is faster than global variables, because you do not need to search the scope chain up.

two. Memory Issues

JavaScript has an automatic garbage collection mechanism, which means that the execution environment is responsible for managing the memory used during code execution. Other languages such as C and C + +, must manually track memory usage, timely release, otherwise it will cause a lot of problems. JavaScript does not need this, and it manages memory allocations and garbage collection on its own.

The most common garbage collection method for JavaScript is tag cleanup. The garbage collector adds tags to the variables stored in memory at run time. It then removes the tag that is using the variable in the environment, and the variable that is not tagged is considered a variable to be deleted. Finally, the garbage collector completes the memory cleanup work, destroys those tagged values, and reclaims the memory space they occupy.

The garbage collector is run periodically, which can cause performance problems for the entire program. For example, a previous version of IE7, its garbage collector runs according to memory allocations, such as 256 variables to start running the garbage collector, so that it has to run frequently, thereby reducing performance.

In general, make sure that you use the least amount of memory to get better performance on your pages. The best way to optimize memory is to set it to NULL to release the reference once the data is no longer useful, which is called dereferencing. This practice applies to most global variables and global objects.

var o = {    ' Lee 'null;                                    // Unbind object references, waiting for garbage collector to recycle

Section 106th, JavaScript variable scope and memory

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.