Detailed JS variable, scope, memory

Source: Internet
Author: User
Tags ming

This article highlights:

1. Difference between a value type and a reference type

2. Copying variable values

3. Memory

4. Passing parameters

5. Implementation environment and scope issues

1. The basic type values are: Undefined,null,boolean,number and string, these types occupy a fixed size space in memory, their values are stored in the stack space , we accessed by value.

(1) value type: Numeric, Boolean, null, undefined.
(2) Reference type: object, array, function.

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 (objects have many properties and methods), they cannot be saved to the stack memory. However, the memory address size is fixed, so the memory address can be stored in the stack memory.

The two differences are as follows:

    1. The base type value occupies a fixed amount of space in memory and is therefore stored in the stack memory;
    2. Copying the value of the base type from one variable to another creates a copy of the value, and the value of the reference type is the object, stored in the heap memory;
    3. A variable that contains a reference type value actually contains not the object itself, but a pointer to that object;
    4. 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;
    5. Determine which base type a value can use the TypeOf operator, and determine which reference type can use the instanceof operator.
    6. 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.
Dynamic properties of the value of the base type and reference type
Nicholas
Undefined

This means that you can add properties only to reference type values dynamically.

In short, heap memory holds reference values, and stack memory holds fixed type values.

<script type= "Text/javascript" >

var man = new Object ();//man points to the space address of the stack memory

Man.name = "Jack";

var man2 = Man;//man2 Gets the point address of Man

alert (man2.name);//two pop-up Jack

alert (man.name);

</script>

2. Copying variable values

Let's look at the following example:

Example one:

var man = new Object ();//man points to the space address of the stack memory

Man.name = "Jack";

var man2 = Man;//man2 Gets the point address of Man

Man2.name = "Ming";//because they all point to the same object, the same name, no matter who modifies it, everyone modifies the

alert (man2.name);//Two pop-up Ming

alert (man.name);

Example two:

5; var num2 = num1;

The value saved in NUM1 is 5. When the value of NUM1 is used to initialize NUM2, the value 5 is also saved in num2. However, 5 in num2 and 5 in NUM1 are completely independent, and this value is just a copy of 5 in NUM1.

Object ();   //Nicholas

The variable obj1 holds a new instance of an object. The value is then copied to the Obj2; in other words,both obj1 and Obj2 point to the same object. This way, when you add the Name property to Obj1, you can access the property through Obj2.

It can be concluded that in the context of variable copying, the basic type and the reference type are different, and the underlying type replicates the value itself, whereas the reference type replicates the address.

3. Memory issues

javascriptHas an automatic garbage collection mechanism that, once the data is no longer in use, can be set to "null" to release the reference

Circular references

A very simple example: A DOM object is referenced by an Javascript object while referencing the same or other JavaScript object, which can cause a memory leak. The reference to this DOM object will not be reclaimed by the garbage collector when the script is stopped. To break a circular reference, the reference to the object or DOM object referencing the DOM element needs to be assigned a value null .

Closed Package

When a variable outside the closure is introduced into the closure, the object cannot be garbage collected (GC) when the closure ends.

function() {  Array (1000000). Join (functionreturn largestr;}} ();
Dom leaks

When the original COM is removed, the child node references are not removed and cannot be reclaimed.

select = Document.queryselector;  Select (' #tree ');  In the COM tree, Leafref is a sub-node of Treefre Select (' body '); Body.removechild (treeref);  #tree不能被回收入, because the treeref is still null;  Null //Now the #tree can be released. 
Timers (fixed) time device leakage

Timers are also a common place to generate memory leaks:

For (90000; i++) {  var buggyobject = {    functionvar val = setTimeout (function  null;}     
Debug memory

ChromeYour own memory debugging tool makes it easy to see memory usage and memory leaks:
Click on the record in Timeline-I:

4. Passing parameters

In ECMAScript, the parameters of all functions are passed by value,

<type="Text/javascript" >     box//pass by value num+=       //That is, the final output should be 20 (output here)</script>

Let's look at an example:
function     Addten10; return num;} var count = 20; var result = Addten (count); alert (count); //20, no change alert (result); //30            
function  Setname "Nicholas";} var person = new Object (); SetName (person); alert (person.name); //"Nicholas"          
SetName(obj) {    "Nicholas";    "Greg"; //"Nicholas"   

If person is passed by reference, the person is automatically modified to point to a new object whose Name property has a value of "Greg".

JavaScript is not passed by reference, and if there is a reference pass, the variables inside the function will be global variables and can be accessed externally. But this is obviously impossible.

5. Execution Environment and scope

The execution environment is one of the javascript most important concepts, and the execution environment defines variables or functions that have access to other data.

The global execution environment is the outermost execution environment, in a Web browser, the global execution environment is an window object, so all functions of global variables are created as window properties and methods.

<type= "text/javascript" >      setName"TRIGKIT4";} alert (//global variable, outermost, The window attribute alert (//global function, outermost, belongs to Window method </script>       

When the execution of the code in the executing environment is completed, the environment is destroyed, and the variables and functions stored therein are destroyed, and if the global environment is complete, all programs must be executed or the Web page is finished before it is destroyed.

Remove the var local variable
<type="Text/javascript" >      setName//Remove var into global variable} setName (); alert (name) ; Eject TRIGKIT4</script>       
By passing a parameter, it is also a local variable
<type="Text/javascript" >      setName//Pass the parameter, also local variable alert (name);} setName ("? Trigkit4 "); //Eject TRIGKIT4 alert (name); //Eject Jack</script>         

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

<type="Text/javascript" >     setNamesetyear;}} alert (Setyear ());  </script>       

You can access it in the following ways:

<type="Text/javascript" >     setNamesetyear//pop up</script> 

Again a scope example:

<script type="Text/javascript" >var name = "Jack";  The scope of the function SetName () { function setyear() { //setyear () method is within setName () var b = "HI"; //variable B has a scope of return within setyear ( ) ;} alert (b);  Unable to access}</script>              

When code executes in an environment, it forms something called a scope chain, which is used to ensure an orderly access to variables and functions that have access in the execution environment (referred to as hierarchy of rules), the front end of the scope chain, and the variable objects of the execution environment.

Scope

A variable is not declared or declared within a function without a VAR is a global variable, has a global scope, window all properties of the object have global scope, can be accessed anywhere in the code, the function is declared inside and Var-modified variables are local variables, can only be used in the function body, The parameters of the function, although not using Var, are still local variables.

No block-level scopes

No block-level scopes

If statement:<type="Text/javascript" >if (the curly brace of the//if statement has no scope function.) "TRIGKIT4";} alert (box); //Eject TRIGKIT4</script>        

The same is true for a For loop statement.

Query for variables

In a variable's query, accessing a local variable is faster than a global variable, so you do not need to search the scope chain up.
Here's an example:

<type="Text/javascript" >     setName</script>    

Each environment can search up the scope chain to query for variables and function names, but any environment cannot enter another execution environment by searching down the scope chain. Here, if you remove it var name = "trigkit4" , the "Jack" will pop up.

Closed Package

When a variable outside the closure is introduced into the closure, the object cannot be garbage collected (GC) when the closure ends.

function() {  Array (1000000). Join (functionreturn largestr;}} ();

Detailed JS variable, scope, 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.