JS variables, scope and memory details _ basic knowledge

Source: Internet
Author: User

The basic type values are: Undefined,null,boolean,number and string, which occupy a fixed amount of space in memory, their values are stored in the stack space, we access 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 that value in heap memory. Because the size of this value is not fixed (objects have many properties and methods), they cannot be saved to stack memory. However, the memory address size is fixed, so you can save the memory address in stack memory.

<script type= "Text/javascript" >
var box = new Object ();//Create a reference type
var box = "Lee";  The base type value is the string
box.age =;  Basic type value adding attributes are weird because only objects can add properties.
alert (box.age);//is not a reference type and cannot be exported;
</script>

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 stack memory
  man.name = "Jack";
  var man2 = Man;//man2 Obtains man's point of Address

  alert (man2.name);///Two pop-up Jack
  alert (man.name);
</script>

Copy variable Value

Let's look at the following example:

<script type= "Text/javascript" >
  var man = new Object ();//man points to the space address of stack memory
  man.name = "Jack";
  var man2 = Man;//man2 Obtains man's point of address

  man2.name = "Ming";//because they all point to the same object, the same name, and whoever modifies it, everyone modifies
  alert (man2.name );//Two Pop-up Ming
  alert (man.name);
</script>

As can be concluded: In the context of variable replication, the base type and reference type are also different, and the base type duplicates the value itself, and the reference type copies the address.

Passing parameters

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

<script type= "Text/javascript" >
   function box (num) {   //pass num+=10 by value
     ;
     return num;
   }

   var num = ten;
   var result = box (num);
   alert (result); If it is passed by reference, then num in the function becomes a similar global variable, and the number outside is replaced by
   alert (num);  That is to say, the final output should be 20 (here output)
</script>

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

Execution Environment and scope

The execution environment is one of the most important concepts in JavaScript, where the execution environment defines a variable or function that has access to other data.

The global execution environment is the outermost execution environment in which the global execution environment is the window object, and therefore all the functions of global variables are created as Windows properties and methods.

<script type= "Text/javascript" >
   var name = "Jack";      Define global variable
   function SetName () {return
     "TRIGKIT4";
   }

   alert (window.name);    Global variable, outermost, belongs to Window Property
   alert (Window.setname ());//global function, outermost, window method
</script>

After the execution of the code within the execution environment has been 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 will be destroyed.

Remove local variables from Var

<script type= "Text/javascript" >
   var name = "Jack";
   function SetName () {
     name = ' TRIGKIT4 ';  Get rid of VAR into global variable
   }

   setname ();
   alert (name);/Popup trigkit4
</script>

is also a local variable by passing a parameter

<script type= "Text/javascript" >
   var name = "Jack";
   function SetName (name) {  //is also a local variable
     alert (name) by passing parameters;

   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

<script type= "Text/javascript" >
   var name = "Jack";
   The scope of the function SetName () {
     function setyear () {  //setyear () method is in SetName ()
       ;
   Alert (Setyear ());//unreachable, error 
</script>

You can access it in the following ways:

<script type= "Text/javascript" >
   var name = "Jack";
   The scope of the function SetName () {
     function setyear () {  //setyear () method is return within SetName ()
       .
     return setyear ();
   }
   Alert (SetName ()); Pop-up
</script>

One More scope example:

<script type= "Text/javascript" >
   var name = "Jack";
   The scope of the function SetName () {
     function setyear () {  //setyear () method is
       var b = "Hi" in SetName ();   The scope of variable B is setyear ()
       .
     alert (b);//Cannot access 
   }
</script>

When the code executes in an environment, is called a scope chain of things, its purpose is to ensure that the implementation of the environment has access to the variables and functions of the orderly access (refers to the rule level to access), the scope of the chain of the front-end, is the execution of the environment variable object.

Scope

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

No block-level scope

No block-level scope

If statement:

<script type= "Text/javascript" >
if (true) {The            curly braces of the//if statement have no scope functionality.

var box = "Trigkit4";
}
alert (box);//pop-up trigkit4
</script>


The same is true for loop statements.

Query for variables

In a query for a variable, accessing a local variable is faster than a global variable, so you do not need to search up the scope chain.
The following example:

<script type= "Text/javascript" >
   var name = "Jack";
   function SetName () {
      var name = ' TRIGKIT4 ';
      return name; Search for variables from bottom up
  }
  alert (SetName ());   
</script>

Memory issues

JavaScript has an automatic garbage collection mechanism that can be set to "null" to release references once the data is no longer in use

Circular Reference

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

Closed Bag

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

var a = function () {
 var largestr = new Array (1000000). Join (' x ');
 return function () {return
  largestr
 }
} ();

Dom leaks

When the existing COM is removed, the child node reference is not removed and cannot be reclaimed.

var select = Document.queryselector;
var treeref = select (' #tree ');

In a COM tree, Leafref is a treefre of the
leafref = select (' #leaf ') of a child node; 
var BODY = Select (' body ');

Body.removechild (treeref);

#tree不能被回收入, because Treeref is still in
//workaround:
treeref = null;

Tree can not be recycled, because the leaf results leafref still
leafref = null;

Now the #tree can be released.

Timers (fixed) time device leakage

Timers are also a common place to generate memory leaks:

for (var i = 0; i < 90000 i++) {
 var buggyobject = {
  callagain:function () {
   var ref = this;
   var val = settimeout (function () {
    ref.callagain ();
   }, 90000);
  }

 Buggyobject.callagain ();
 Although you want to recycle, but timer is still
 buggyobject = null;
}

Debug memory

Chrome's own memory debugging tool makes it easy to see memory usage and memory leaks:
Click the record at Timeline-> 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.