[Front-end Knowledge Points] Details js variables, scopes and memory

Keywords: Javascript ECMAScript Windows

The basic type values are undefined, NUll, Boolean, Number and String, which occupy a fixed size space in memory, and their values are stored in stack space, which we access by value.

(1) Value type: numerical value, Boolean value, 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 these values is not fixed (objects have many attributes and methods), they cannot be stored in stack memory. But the memory address size is fixed, so the memory address can be stored in stack memory.

<script type="text/javascript">
var box = new Object();  //Create a reference type
var box = "trigkit4";   //The basic type value is a string
box.age = 21;    //Adding attributes to base type values is weird because only objects can add attributes.
alert(box.age);  //It is not a reference type and cannot be output.
</script>

In short, heap memory stores reference values, and stack memory stores fixed type values. Reference is a pointer to the actual location of an object.

It should be noted here that references point to specific objects, not to another reference.

The objects here can be string objects, number objects, array objects, etc.

<script type="text/javascript">
    var man = new Object();//man points to the spatial address of stack memory
    man.name = "Jack";
    var man2 = man;//man2 obtains man's directional address
    
    alert(man2.name);//Both pop up Jack
    alert(man.name);
</script>

Duplicate variable values

Let's look at the following example:

<script type="text/javascript">
    var man = new Object();//man points to the spatial address of stack memory
    man.name = "Jack";
    var man2 = man;//man2 obtains man's directional address
    
    man2.name = "ming";//Because they all point to the same object, the same name, no matter who changes it, everyone changes it.
    alert(man2.name);//Both pop up ming
    alert(man.name);
</script>

From the above, it can be concluded that in variable replication, the basic type and reference type are also different. The basic type replicates the value itself, while the reference type replicates the address.

Transfer parameters

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

<script type="text/javascript">
     function box(num){      //Transmission by value
         num+=10;
         return num;
     }
     
     var num = 10;
     var result = box(num);
     alert(result);  //If passed by reference, num in the function becomes a global variable, replacing the number outside.
     alert(num);    //That is to say, output 20 (output 10 here)
</script>

js is not passed by reference, if there is a reference passing, then the variables in the function will be global variables, which can also be accessed externally. But this is clearly impossible.

Implementation environment and scope

Execution environment is one of the most important concepts in javascript. Execution environment defines variables or functions that have access to other data.

The global execution environment is the most peripheral execution environment. In web browsers, the global execution environment is a window object. Therefore, all functions of global variables are created as windows attributes and methods.

<script type="text/javascript">
      var name = "Jack";           //Define global variables
      function setName(){
          return "trigkit4";
      }
      
      alert(window.name);        //Global variables, the most peripheral, belong to the window property
      alert(window.setName());  //Global function, the most peripheral, belongs to window method
</script>

When the code in the execution environment is executed, the environment is destroyed, and the variables and functions stored in it are destroyed. If it is a global environment, it will be destroyed only after the execution of all programs or the completion of web pages.

Remove local variables of var

<script type="text/javascript">
      var name = "Jack";
      function setName(){
          name = "trigkit4";   //Getting rid of var becomes a global variable
      }
      
      setName();
      alert(name);//Trigkit 4 pops up
</script>

Through parameter transfer, it is also a local variable.

<script type="text/javascript">
      var name = "Jack";
      function setName(name){    //Through parameter transfer, it is also a local variable.
          alert(name);
      }
      
      setName("trigkit4");//Trigkit 4 pops up
      alert(name);//Pop up Jack
</script>

Functions are also included in the body of the function, which is the only function that can access the functions in the inner layer.

<script type="text/javascript">
     var name = "Jack";
      function setName(){
          function setYear(){    //The scope of the setYear() method is within setName().
              return 21;
          }
      }
      alert(setYear());//Unaccessible, error 
</script>

Access can be done by:

<script type="text/javascript">
     var name = "Jack";
      function setName(){
          function setYear(){    //The scope of the setYear() method is within setName().
              return 21;
          }
          return setYear();
      }
      alert(setName()); //Pop up 21
</script>

Another scoping example:

<script type="text/javascript">
     var name = "Jack";
      function setName(){
          function setYear(){    //The scope of the setYear() method is within setName().
              var b = "hi";     //The scope of variable b is in setYear().
              return 21;
          }
          alert(b);//cannot access 
      }
</script>

When code is executed in an environment, it will form a kind of thing called scope chain. Its purpose is to ensure that variables and functions with access rights in the execution environment are accessed in an orderly manner (referring to access according to the rule hierarchy). The front end of the scope chain is the variable object of the execution environment.

Scope of action

Variables that are not declared or declared in a function without VaR are global variables, which have global scope, and all attributes of window objects have global scope; they can be accessed anywhere in the code. Variables declared and modified with VaR in a function are local variables, which can only be used in the body of the function. Although the parameters of the function do not use var, they are still local. Variables.

No block-level scope

// if statement:
<script type="text/javascript">
if(true){                        //The curly brackets of the if statement have no scope function.

var box = "trigkit4";
}
alert(box);//Trigkit 4 pops up
</script>

The same is true for loop statements.

Query of variables

In the query of variables, it is faster to access local variables than global variables, so there is no need to search up the scope chain.
The following examples are given:

<script type="text/javascript">
     var name = "Jack";
      function setName(){
           var name = "trigkit4";
           return name;  //Search for variables from the bottom up
    }
    alert(setName());       
</script>

Each environment can search up the scope chain to query variables and function names; however, no environment can enter another execution environment by searching down the scope chain. Here, if var name = trigkit4 is removed, then "Jack" will pop up.

Memory problem

javascript has an automatic garbage collection mechanism, which can be set to "null" to release references once data is no longer used

Circular reference

A simple example: A DOM object is referenced by a Javascript object and at the same time by the same or other Javascript object, which may cause memory leaks. References to this DOM object will not be reclaimed by the garbage collector when the script stops. To destroy circular references, references to objects that reference DOM elements or DOM objects need to be assigned null.

closure

When variables outside the closure are 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 leakage

When the original COM is removed, the sub-node reference can not be recovered without being removed.

var select = document.querySelector;
var treeRef = select('#tree');

//leafRef is a sub-node of treeFre in COM tree
var leafRef = select('#leaf'); 
var body = select('body');

body.removeChild(treeRef);

//# tree cannot be reclaimed because treeRef is still there
//Solution:
treeRef = null;

//tree can't be recycled yet, because leafRef is still there as a result of the leaves.
leafRef = null;

//Now # tree can be released.

Timers Meter (Timer) Leakage

Timers are also common places where memory leaks occur:

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, timer is still there
  buggyObject = null;
}

Debug memory

Chrome's own memory debugging tool makes it easy to view memory usage and memory leaks:
Click record at Timeline - > Memory:

Related articles:

Explain js closures in detail

We can use closures to break through the scope chain. Explain js closures in detail





Original address: https://segmentfault.com/a/1190000000687844

Posted by mithril on Sun, 26 May 2019 12:14:10 -0700