The JS variable is loosely typed (not mandatory) and determines that it is only a name used to hold a particular value at a particular time;
Because there is no rule that defines what data type value A variable must hold, the value of a variable and its data type can be changed within the script's lifecycle;
A variable and scope
1. Basic types and reference types
The JS variable contains values of two different data types: the base type value and the reference type value;
1. Basic type value: The existence of a simple data segment in the stack memory, that is, this value is completely stored in the memory of a location;
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, we access by value;
2. Reference type value: Preserving objects in heap memory (which may consist of multiple values), in which the variable is actually a pointer to another location in memory, where the object is saved;
The value of the reference type is not fixed, so it cannot be saved in stack memory and must be stored in heap memory, but the memory address of the value of the reference type can be saved in the stack memory;
When querying a variable of a reference type, the memory address is read from the stack memory, and then the value in the heap memory is found by the address;=> accessed by reference;
2. Dynamic Properties
You define basic type values and reference type values in a similar way: Create a variable and assign a value to the variable;
However, when this value is saved to a variable, the operations that can be performed on different types of values are not the same;
var box = new Object (); Create a reference type;
Box.name = ' Lee '; Add a property;
Console.log (box.name); =>lee;
var box = ' Lee '; Create a basic type
box.age =; Add attributes to the base type;
Console.log (box.age); =>undefined;
3. Copy variable values
The basic type and reference type are also different in the context of variable replication;
The value itself is assigned to the base type;
var box = ' Lee '; Generate a box ' Lee ' in stack memory;
var box2 = box; Regenerate in stack memory into a box2 ' Lee ';
box and Box2 are completely independent, and two variables do not affect
each other when they are operated separately. The reference type assigns a value to the address;
var box = new Object (); Create a reference type; box in stack memory; object in heap memory
; Box.name = ' Lee '; Add a property;
var box2 = box; Assigning the reference address to the box2;box2 in stack memory;
Box2=box, because they point to the same object;
If the name attribute in this object is modified, the values of Box.name and box2.name output are modified;
4. Pass Parameters
The parameters of all functions in JS are passed by value, that is, the parameters are not passed by reference;
function box (num) { //passed by value, passing parameters are basic types;
Num +=10; Num Here is a local variable, the global is invalid;
return num;
}
var num =;
var result = box (num);
Console.log (result); ;
Console.log (num); ;
function box (num) {return
num;
}
Console.log (num); NUM is not defined;
function box (obj) {
obj.name = ' Lee ';
var obj = new Object (); An object is created inside the function, which is a local variable, but is destroyed
at the end of the function; Obj.name = ' Mr '; Did not replace the original obj;
}
var p = new Object ();
Box (p); The variable p is copied to obj after being passed into the box () function, and obj and P are accessing the same object
within the function. Console.log (p.name); =>lee;
The parameters of the JS function will be local variables, that is to say, are not passed by reference;
5. Detection type
To detect the type of a variable, judge by the TypeOf operator class;
More used to detect the basic type;
var box = ' Lee ';
Console.log (typeof box); =>string;
To detect what type of object The variable is, see through the instanceof operator;
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); Whether the =>true; is a string object;
var box5 = ' string ';
Console.log (box5 instanceof String); =>false;
When using instanceof to check the value of the base type, it returns false;
6. Implementation environment and scope
Execution Environment: Defines the other data that a variable or function has access to, and determines their respective behavior;
In a Web browser, the global execution Environment =window object;
Therefore, all global variables and functions are created as properties and methods of the Window object; var box = ' Blue ';
declares a global variable; function Setbox () {console.log (box);
Global variables can be accessed in functions; } setbox ();
execution function;
The global variable =window the properties of the object;
The method of global function =window object;
PS: When all the code in the execution environment is finished, the environment is destroyed, and all the variables and function definitions stored therein are destroyed;
If it is in the global environment, the execution of the program needs to be completed, or the Web page is closed before it is destroyed;
PS: Each execution environment has a variable object associated with it, just like the global window can call global variables and global methods;
The local environment also has a window-like variable object, and all variables and functions defined in the environment are stored in this object;
(We cannot access this variable object, but the parser will use it in the background when processing the data);
var box = ' Blue '; function Setbox () {var box = ' Red ';
Here is the local variable, the value in the body of the current function is ' red '; the function body is not recognized;
Console.log (box);
} setbox ();
Console.log (box);
You can replace local variables in the body of a function by passing parameters, but the scope is limited to this local environment in the function body;
var box = ' Blue ';
function Setbox (box) {//) replaces local variables with global variables by passing parameters; alert (box);
The value of box at this time is the argument passed in when the external call;=>red;
} setbox (' Red ');
alert (box);
If the function body also contains a function, only this internal function can access the outer layer of the function of the variable; The internal environment can access all external environments through the scope chain, but the external environment cannot accessAny variables and functions in the internal environment;
var box = ' Blue ';
function Setbox () {function setcolor () {var b = ' Orange ';
alert (box);
alert (b); } setcolor ();
The execution Environment of SetColor () is in Setbox ();
} setbox ();
PS: Each function is called to create its own execution environment, when executed to this function, the environment of the function will be pushed to the environment stack to execute, and after the implementation of the Environment stack pop-up (exit), the control to the implementation of the environment at the level; PS: When a contemporary code executes in an environment, it forms something called a scope chain; its purpose is to ensure the orderly access to variables and functions that have access to the execution environment; The front-end 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, which is removed after the code executes;
With statement and Try-catch statement; both statements add a variable object to the front of the scope chain;
With statement: Adds the specified object to the scope chain;
Catch statement: Creates a new variable object that contains the declaration of the wrong object being thrown;
function BuildUrl () {
var qs = '? Debug=true ';
The WITH (location) { //The WITH statement receives the location object, so the variable object contains all the properties and methods of the location object;
var url = href+qs; And this variable object is added to the front-end of the scope chain;
return URL;
8. No block-level scopes
Block-level scope: Represents a block of code that has curly braces, such as an if statement, and therefore supports conditional judgments to define variables;
if (true) { //If statement code block has no local scope;
var box = ' Lee '; A variable declaration adds a variable to the current execution environment (here is the Global environment);
}
alert (box);
for (var i=0 i<10; i++) { //created variable I will still exist in the execution environment outside the loop even after the for loop execution ends;
var box = ' Lee ';
}
alert (i);
alert (box);
function box (num1,num2) {
var sum = num1+num2; At this point sum is a local variable; if the var,sum is removed, it is a global variable;
return sum;
}
Alert (Box (10,10));
alert (sum); The
sum is not defined; PS: It is not recommended to initialize variables without using Var, as this method can cause various surprises;
Generally, a variable is searched to determine what the identifier actually represents; Search by: up-step query;
var box = ' Blue ';
function Getbox () {return
box; box is a global variable, and if it is var box= ' Red ', then it becomes a local variable;
Alert (Getbox ());
The variable box is referenced when Getbox () is invoked;
First, search the variable object of Getbox () to find the identifier named box;
Then, the search continues to the next variable object (the Global Environment's variable object), and the box identifier is found;
PS: In a variable query, accessing local variables is faster than global variables because there is no need to search up the scope chain;
Two memory problems
JS has automatic garbage collection mechanism, the execution environment is responsible for managing the memory used in the execution of the code, it will manage the memory allocation and garbage memory recovery;
JS is the most commonly used garbage collection method is to mark the elimination of the garbage collector will be stored in memory at the time of the variable tag;
It then removes the tag of the variable being used in the environment, and the variable that is not removed is considered a variable to be deleted;
Finally, the garbage collector completes the memory cleanup work, destroys those tagged values and reclaims the memory space they occupy;
Garbage collectors are run periodically, which can cause performance problems throughout the program;
For example, the previous version of IE7, his garbage collector is based on memory allocations run, such as 256 variables began to run the garbage collector, which has to run frequently, thereby reducing performance;
In general, ensuring that the least amount of memory is used allows the page to achieve better performance;
Best practice: Once the data is no longer in use, set its value to NULL to release the reference, which is called a dereference;
var o = {
name: ' Lee ';
};
o = null; Dismiss object references and wait for garbage collector to recycle;
Three summary
1. Variable
The JS variable can hold two types of values: the base type value and the reference type value, and they have the following characteristics:
1. The basic type value occupies the fixed size space in the memory, therefore is saved in the stack memory;
2. Copying a value of the base type from one variable to another creates a copy of the value;
3. The value of the reference type is the object, which is stored in the heap memory;
4. A variable containing a reference type value actually contains not the object itself, but a pointer to the object;
5. Copy the value of a reference type from one variable to another, which is actually the pointer, so the two variables end up pointing to an object;
6. It is possible to use the TypeOf operator to determine what basic type a value is, and to determine which reference type a value is can use the instanceof operator;
2. Scope
All variables exist in an execution environment (scope), which determines the life cycle of the variable and which part of the code can access the variable;
1. The execution environment is divided into global execution environment and function execution environment;
2. Each time a new execution environment is entered, a scope chain is created to search for variables and functions;
3. The local environment of the function not only has access to the variables in the scope of the function, but also has access to its parent environment and even the global environment;
4. The execution environment of variables helps to determine the appropriate release of memory;
3. Memory
JS Automatic garbage collection mechanism
1. The value leaving the scope will be automatically marked as recyclable and will be deleted during garbage collection;
2. In order to ensure the efficient recovery of memory, the global object/global object properties that are no longer in use and references to circular reference variables should be released in time;