The JavaScript variable scope and memory

  • 2020-05-27 04:12:52
  • OfStack

The JS variable is loose (not typed) in nature, determining that it is just a name used to hold a particular value at a particular time;
Since there are no rules that define what data type values a variable must hold, the value of the variable and its data type can change over the life of the script.

1 variables and scopes
1. Base and reference types

// JS variable contains values of two different data types: base type value and reference type value;

// 1. Basic type value: a simple data segment stored in the stack memory; That is, the value is completely stored in one location in memory.
// basic type values include :Undefined|, Null|, Boolean|, Number|, String;
// these types occupy a fixed amount of space in memory; Their values are stored in the stack space and we access them by value;

// 2. Reference type value: an object stored in heap memory (which may consist of multiple values), that is, a variable is actually only holding a pointer to another location in memory where the object is stored;
// the value of the reference type is not fixed in size, so it cannot be stored in stack memory, but must be stored in heap memory; But you can store the memory address of the value of the reference type in stack memory.
// when querying for variables of reference type, first read the memory address from the stack memory, and then find the value in the heap memory through the address; = > Access by reference;

2. Dynamic properties


//  Defining base type values is similar to referencing type values : create 1 And assign a value to that variable ;
//  But when this value is saved into a variable , Operations that can be performed on different types of values are not 1 sample ;
  var box = new Object();           //  Create a reference type ;
  box.name = 'lee';              //  new 1 A property ;
  console.log(box.name);           // =>lee;

  var box = 'lee';              //  Creating a base type 
  box.age = 15;                //  Add attributes to the base type ;
  console.log(box.age);            // =>undefined;

3. Copy variable values


//  In terms of variable replication , The base and reference types are also different ;
//  The base type assigns the value itself ;
  var box = 'lee';              //  Generated in stack memory 1 a box'lee';
  var box2 = box;               //  Regenerate in stack memory 1 a box2'lee';
  // box and box2 Completely independent ; The two variables operate independently ;

//  The reference type is assigned an address ;
  var box = new Object();          //  create 1 Individual reference types ;box In stack memory ; while Object In heap memory ;
  box.name = 'lee';             //  new 1 A property ;
  var box2 = box;              //  Assign the reference address to box2;box2 In stack memory ;
  // box2=box, Because they're pointing to the same thing 1 An object ;
  //  So if I have this object name The property has been modified ,box.name and box2.name The value of the output will be changed ;

4. Pass parameters


// JS All function parameters are passed by value , That is, the parameter is not passed by reference ;
  function box(num){             //  Pass by value , The parameters passed are basic types ;
    num +=10;               //  Here, num It's a local variable , Global is invalid ;
    return num;
  }
  var num = 50;
  var result = box(num);
  console.log(result);           // 60;
  console.log(num);             // 50;

  function box(num){
    return num;
  }
  console.log(num);             // num is not defined;

  function box(obj){
    obj.name = 'lee';
    var obj = new Object();       //  The function is created inside again 1 An object , It's a local variable ; But it's destroyed at the end of the function ;
    obj.name = 'Mr';           //  I didn't replace it obj;
  }
  var p = new Object();
  box(p);                 //  variable p Be passed to the box() The function is then copied to obj; Inside the function ,obj and p It's the same 1 An object ;
  console.log(p.name);           // =>lee;

  // JS The arguments to the function will all be local variables ; That is to say, , Not passed by reference ;

5. Detection type


//  To detect 1 The type of a variable , through typeof Operator class judgment ;
//  Used to detect basic types ;
  var box = 'lee';
  console.log(typeof box);          // =>string;

//  What type of object is a variable to detect , through instanceof Operator to see ;
  var box = [1,2,3];
  console.log(box instanceof Array);     // =>true;
  var box2 = {};
  console.log(box2 instanceof Object);
  var box3 = /g/;
  console.lgo(box3 instanceof RegExp);
  var box4 = new String('lee');
  console.log(box4 instanceof String);   // =>true; Is it a string object ;

  var box5 = 'string';
  console.log(box5 instanceof String);   // =>false;
  //  When using instanceof When checking the value of the base type , It will be returned false;

6. Execution environment and scope


//  The execution environment : Defines other data that a variable or function has access to , It determines their individual behavior ;
//  in Web The browser , Global execution environment =window object ;
//  Therefore, all global variables and functions are as window Object properties and methods are created ;
  var box = 'blue';             //  The statement 1 Global variables ;
  function setBox(){
    console.log(box);           //  Global variables can be accessed in functions ;
  }  
  setBox();                 //  Executive function ;
  //  Global variable =window Properties of an object ;
  //  Global function =window Object method ;

// PS: When all the code in the execution environment has been executed , The environment was destroyed , All variables and function definitions stored in it are destroyed ;
//  If you're in a global environment , The program needs to finish executing , Or the page will be destroyed when it is closed ;

// PS: Each execution environment has one 1 A variable object associated with it , It's like global window Global variables and global methods can be called 1 sample ;
//  The local environment does too 1 A similar window Variable object of , All variables and functions defined in the environment are stored in this object ;
// ( We cannot access the variable object , But the parser USES it in the background as it processes the data );
  var box = 'blue';
  function setBox(){
    var box = 'red';           //  Here are the local variables , The value in the body of the current function is 'red'; It's not recognized outside the body ;
    console.log(box);
  }  
  setBox();
  console.log(box);

//  Local variables in a function can be replaced by passing arguments , But the scope is limited to this local environment within the body of the function ;
  var box = 'blue';
  function setBox(box){           //  Through the participation , Replace local variables with global variables ;
    alert(box);              //  At this time box Is the parameter passed in when the external call is made ;=>red;
  }
  setBox('red');
  alert(box);

//  If the function has a function inside it , Only this inside function can access the outside 1 The variables of the function of the layer ;
//  Internal environments can access all external environments through a scope chain , But the external environment cannot access any of the variables and functions in the internal environment ;
  var box = 'blue';
  function setBox(){
    function setColor(){
      var b = 'orange';
      alert(box);
      alert(b);
    }
    setColor();              // setColor() The execution environment in setBox() Within the ;
  }
  setBox();
  // PS: Each function creates its own execution environment when it is called ; When this function is executed , The function's environment is then pushed onto the environment stack for execution , After execution, it pops up in the environment stack ( exit ), Hand over control 1 Level execution environment ;

  // PS: When the code in 1 When executed in two environments , Can form 1 Something called a scope chain ; Its purpose is to ensure orderly access to variables and functions that have access rights in the execution environment ; The front end of the scope chain , Is the variable object of the execution environment ;

7. Lengthen the scope chain


//  Some statements can be added temporarily at the front end of the scope chain 1 Variable object , The variable object is removed after the code is executed ;
// with Statements and try-catch statements ; Both statements are added at the front end of the scope chain 1 Variable object ;
// with statements : The specified object is added to the scope chain ; 
// catch statements : Will create 1 Two new variable objects , This contains the declaration of the thrown error object ;
  function buildUrl(){
    var qs = '?debug=true';
    with(location){            // with The statement receives location object , So the variable object is included location All properties and methods of the object ;
      var url = href+qs;        //  This variable object is added to the front end of the scope chain ;
    };
    return url;
  }

8. No block-level scope


//  Block-level scopes : Such as said if A block of code enclosed in curly braces, such as a statement , so , Support conditional judgment to define variables ;
  if(true){                 // if A block of statement code has no local scope ;
    var box = 'lee';           //  Variable declarations add variables to the current execution environment ( In this case, the global environment );
  }
  alert(box);

  for(var i=0; i<10; i++){         //  Variables created i Even in the for When the loop is over , It will still exist in the execution environment outside the loop ;
    var box = 'lee';
  }
  alert(i);
  alert(box);

  function box(num1,num2){
    var sum = num1+num2;         //  At this time sum It's a local variable ; If you remove var,sum It's a global variable ;
    return sum;
  }
  alert(box(10,10));
  alert(sum);                // sum is not defined; Can't access sum;
  // PS: It is not recommended not to use var You initialize the variable , Because this method can lead to all kinds of accidents ;

// 1 Generic variables are searched to determine what the identifier actually stands for ; search : Step up ;
  var box = 'blue';
  function getBox(){
    return box;              //  At this time box It's a global variable ; If it is var box='red', That becomes a local variable ;
  }
  alert(getBox());              
  //  call getBox() Will reference variables box;
  //  First of all, , search getBox() Variable object of , Look for, box The identifier ;
  //  then , Let's keep searching 1 Variable object ( The variable object of the global environment ), To find the box identifier ;
// PS: In variable queries, it is faster to access local variables than global variables, because there is no need to search up the scope chain; 

2 memory problems


// JS There is an automatic garbage collection mechanism , The execution environment is responsible for managing the memory used during code execution ; It manages its own memory allocation and garbage collection ;

// JS The most common garbage collection method is tag removal ; The garbage collector marks variables stored in memory at run time ;
//  then , It removes the tags of the variables being used in the environment , Variables that are not marked out will be treated as variables to be deleted ;
//  The last , The garbage collector does the memory cleaning , Destroy the values of those tags and reclaim the memory space they occupy ;

//  The garbage collector runs periodically , This can lead to performance problems for the entire program ;
//  Such as IE7 Previous version , His garbage collector runs on memory allocations , Such as 256 The garbage collector starts to run with the variables , So you have to run it frequently , This reduces performance ;

// 1 Generally speaking , Ensuring minimal memory usage results in better page performance ;
//  The best solution :1 The data is no longer in use , Set its value to null To release the reference , This is called de-referencing ;
  var o = {
    name:'lee';
  };
  o = null;               //  Dereference of objects , Wait for garbage collector collection ;

3 summary

1. The variable
// JS variable can hold two types of values: base type value and reference type value; They have the following characteristics:
// 1. The basic type value occupies a fixed space in memory, so it is saved in the stack memory;
// 2. Copy the value of the basic type from one variable to another, and one copy of the value will be created;
// 3. The value of reference type is object, which is stored in heap memory;
// 4. The variable containing the value of the reference type actually contains not the object itself, but a pointer to the object;
// 5. Copy the value of reference type from one variable to another. What is copied is actually a pointer, so both variables eventually point to an object.
// 6. Determine which base type of a value can be used with the typeof operator; You can use the instanceof operator to determine which reference type a value is.

2. Scope
// all variables exist in an execution environment (scope) that determines the life cycle of the variable and which part of the code can access the variables.
// 1. Execution environment can be divided into global execution environment and functional execution environment;
// 2. Every time you enter a new execution environment, a scope chain is created to search for variables and functions;
// 3. The local environment of a function has access not only to variables within the scope of the function, but also to its parent environment and even to the global environment;
// 4. The execution environment of variables is helpful to determine that memory should be properly freed;

3. The memory
// JS automatic garbage collection mechanism
// 1. Out-of-scope values will be automatically marked as recyclable and will therefore be deleted during garbage collection;
// 2. In order to ensure effective memory recovery, global object/global object properties and circular reference variables should be removed in time;


Related articles: