JavaScript variables, scopes and memory, javascript
JS variables are the essence of a loose type (not forced type), which determines that they are only used to save a name for a specific value at a specific time;
Because there is no rule to define the data type value that a variable must save, the value of the variable and its data type can be changed within the lifecycle of the script;
A variable and scope
1. Basic type and reference type
// The JS variable contains two different data types: basic type value and reference type value;
// 1. Basic Type value: A simple data segment stored in the stack memory, that is, this value is completely stored in a location in the memory;
// Basic type values include: Undefined | Null | Boolean | Number | String;
// These types occupy a fixed size of space in the memory; their values are stored in the stack space, which is accessed by value;
// 2. reference Type value: the object stored in the heap memory (which may consist of multiple values). That is, the variable is actually a pointer, which points to another location in the memory, this location stores objects;
// The value of the reference type is not fixed, so it cannot be saved in stack memory and must be saved in heap memory; however, the memory address of the reference type value can be stored in the stack memory;
// When querying referenced variables, read the memory address from the stack memory and find the value in the heap memory through the address; => access by reference;
2. dynamic attributes
// The method for defining the basic type value is similar to that of the reference type value: Create a variable and assign a value to the variable; // After the value is saved to the variable, operations that can be performed on different types of values are different; var box = new Object (); // create a reference type; box. name = 'lil'; // adds an attribute; console. log (box. name); // => lee; var box = 'Lee '; // create a basic type box. age = 15; // Add attributes to the basic type; console. log (box. age); // => undefined;
3. Copy the variable value
// In terms of variable replication, the basic type and reference type are also different; // The value itself is assigned to the basic type; var box = 'lil '; // generate a box 'lil' in the stack memory; var box2 = box; // generate a box2 'lil' in the stack memory; // the box and box2 are completely independent; when the two variables are operated separately, they do not affect each other; // The address assigned by the reference type; var box = new Object (); // create a reference type; box is in the stack memory; the Object is in the heap memory; box. name = 'lil'; // Add an attribute; var box2 = box; // assign the reference address to box2; box2 in the stack memory; // box2 = box, because they point to the same object; // if the name attribute of this object is modified, box. both name and box2.name output values are modified;
4. PASS Parameters
// Parameters of all functions in JS are passed by value, that is, parameters are not passed by reference; function box (num) {// pass by value, the transmitted parameters are the basic type; num + = 10; // The num here is a local variable and the global variable 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 = 'lil'; var obj = new Object (); // another Object is created in the function, which is a local variable, but is destroyed at the end of the function; obj. name = 'Mr '; // The original obj is not replaced;} var p = new Object (); box (p); // Variable p is passed to box () in the function, the object is copied to obj. In the function, obj and p access the same object. log (p. name); // => lee; // parameters of JS functions are local variables; that is, they are not passed by reference;
5. Detection type
// You can use the typeof operator to check the type of a variable. // you can use the typeof operator to check the basic type. var box = 'lil'; console. log (typeof box); //> string; // you can use the instanceof operator to check the type of the variable. 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 ('lil'); console. log (box4 instanceof String); // => true; whether it is a string object; var box5 = 'string'; console. log (box5 instanceof String); // => false; // when instanceof is used to check the value of the basic type, it returns false;
6. Execution Environment and scope
// Execution environment: defines other data that variables or functions have the right to access and determines their respective behaviors. // in a Web browser, the global execution environment is a window object; // Therefore, all global variables and functions are created as properties and methods of the window object; var box = 'blue'; // declare a global variable; function setBox () {console. log (box); // global variables can be accessed in the function;} setBox (); // execute the function; // global variables = properties of the window object; // global function = window object method; // PS: After all the code in the execution environment is executed, the environment is destroyed, all the variables and function definitions stored in them are also destroyed. // if the program is executed in a global environment, or the webpage is disabled, the program is destroyed. // PS: each execution environment has a variable object associated with it, just like a global window can call global variables and global methods; // The local environment also has a variable object similar to window, And all variables and functions defined in the environment are saved in this object; // (we cannot access this variable object, but the parser will use it in the background when processing data); var box = 'blue'; function setBox () {var box = 'red'; // here is the local variable, the value in the current function body is 'red'. When the function body is generated, it is not recognized. console. log (box) ;}setbox (); console. log (box); // you can replace the local variables in the function body by passing parameters, but the scope is limited to the local environment in the function body; var box = 'blue'; function setBox (box) {// Replace the local variable with the global variable by passing the parameter; alert (box); // at this time, the box value is the parameter passed in during external calls; => red ;} setBox ('red'); alert (box); // if the function contains a function, only the internal function can access the variable of the function on the external layer; // The internal environment can access all external environments through the scope chain, but the external environment cannot access any variables and functions in the internal environment; var box = 'blue'; function setBox () {function setColor () {var B = 'Orange '; alert (box); alert (B) ;}setcolor (); // setColor () execution environment in setBox () ;} setBox (); // PS: each function is called and its own execution environment is created. When this function is executed, the function environment will be pushed to the Environment stack for execution, and the execution will pop up (exit) in the environment stack, and the control will be handed over to the upper-level execution environment; // PS: when code is executed in an environment, it forms something called a scope chain. It is used to ensure orderly access to variables and functions with access permissions in the execution environment; the frontend of the scope chain is the variable object of the execution environment;
7. extend the scope chain
// Some statements can temporarily Add a variable object to the front end of the scope chain. The variable object will be removed after code execution; // with statement and try-catch statement; both statements Add a variable object to the front end of the scope chain; // with statement: the specified object is added to the scope chain; // catch statement: A new variable object will be created, including the declaration of the thrown error object; function buildUrl () {var qs = '? Debug = true'; with (location) {// The with statement receives the location object, so the variable object contains all the attributes and methods of the location object; var url = href + qs; // and the variable object is added to the frontend of the scope chain;}; return url ;}
8. No block-level scope
// Block-level scope: indicates a block with curly braces, such as an if statement. Therefore, conditional judgment is supported to define variables. if (true) {// if statement code block does not have a local scope; var box = 'lil'; // The variable declaration adds the variable to the current execution environment (here the global environment is used );} alert (box); for (var I = 0; I <10; I ++) {// variable I is created even after the for loop is executed, it will still exist in the execution environment outside the loop; var box = 'lil';} alert (I); alert (box); function box (num1, num2) {var sum = num1 + num2; // sum is a local variable at this time; If var is removed, sum is the global variable; return sum;} alert (box )); alert (sum); // sum is not defined; sum cannot be accessed; // PS: Variable Initialization is not recommended if var is not used, because this method may cause various accidents; // generally, the variables are searched to determine what the identifier actually represents. The search method is: Query up and down; var box = 'blue'; function getBox () {return box; // at this time, box is a global variable; If var box = 'red', it becomes a local variable;} alert (getBox (); // call getBox () will reference the variable box; // first, search for the variable object of getBox (), find the identifier named box; // then, search for the next variable object (the variable object in the global environment) and find the box identifier. // PS: in variable query, accessing local variables is faster than global variables, because the domain chain does not need to be searched up;
2. Memory problems
// JS has an automatic garbage collection mechanism, and the Execution Environment is responsible for managing the memory used during code execution; it manages memory allocation and useless memory collection by itself; // The most common garbage collection method in JS is Mark clearing. The Garbage Collector will mark the variables stored in the memory at runtime. // then, it will remove the tags of variables being used in the environment, and variables that are not removed will be considered as the variables to be deleted; // Finally, the garbage collector completes memory cleanup, destroy the Marked Values and recycle the memory space they occupied; // The Garbage Collector runs cyclically, which causes performance problems for the entire program; // For example, IE7 earlier versions, the garbage collector runs based on the amount of memory allocated. For example, the garbage collector starts to run with 256 variables, so it has to run frequently to reduce performance. // in general, ensure that the least memory is used to improve the performance of the page; // The best solution: once the data is no longer used, set its value to null to release the reference. This is called removing the reference; var o = {name: 'lil';}; o = null; // release the object reference and wait for the garbage collector to recycle it;
Summary
1. Variables
// JS variables can save two types of values: basic type values and reference type values. They have the following features:
// 1. The basic type value occupies a fixed size in the memory and is stored in the stack memory;
// 2. Copy a value of the basic type from one variable to another, and a copy of the value will be created;
// 3. The value of the reference type is an object and is stored in the heap memory;
// 4. Variables containing reference type values actually contain a pointer to the object instead of the object itself;
// 5. Copy the reference type value from one variable to another, and copy the pointer. Therefore, both variables finally point to an object;
// 6. Determine which basic type of a value can use the typeof operator, and determine which reference type of a value can use the instanceof operator;
2. Scope
// All variables exist in an execution environment (scope), which determines the life cycle of the variables and which part of the code can access the variables;
// 1. The execution environment can be divided into a global execution environment and a function execution environment;
// 2. Each time you enter a new execution environment, a scope chain is created for searching variables and functions;
// 3. The local environment of the function not only has the right to access the variables in the function scope, but also has the right to access the parent environment and even the global environment;
// 4. The execution environment of the variable helps determine that the memory should be properly released;
3. Memory
// JS automatic garbage collection mechanism
// 1. The value of the exit scope will be automatically marked as recoverable, so it will be deleted during garbage collection;
// 2. To ensure effective memory recovery, you should promptly remove the Global Object/Global object attributes that are no longer in use and reference the circular reference variable;