JavaScript-- the scope of variables and memory problems

JS variables used to store data and the reference base value type data types

JS basic value types: Undefined, Null, Boolean, Number, String five kinds; they are stored in the stack memory, you can directly manipulate their value.

JS reference value is based on the type of objects stored in the form of heap memory, JS does not allow direct access to the heap, so the operation of the object is actually referenced in the operation of the object.

JS dynamic properties

Reference types can be added to its dynamic properties and methods, the following code demonstrates how to add a name attribute of an object named person:

var person=new Object();
person.name="bobo";
console.log(person.name);

JS dynamic property is a reference to a data type in terms of, not the basic value types.

Copy JS variables

After the basic value type copying data from one variable to another variable, two independent variables, for them to operate independently of each other.

After the data is copied from a reference type variable to another variable, two variables still refer to the same object, changing one of the variables, it will affect the other.

var person=new Object();
person2=person;
person.name="bobo2";
console.log(person.name+"---"+person2.name);//bobo2---bobo2

JS execution environment with a scope

JS execution environment variables and functions contained , the maximum execution environment called global environment;

Each function has its own JS execution environment, functions upon execution environment will be pressed into the stack after the function completes environment will eject it from the stack. The execution flow control to the execution environment before.

Code in the implementation process, will create a variable of the scope chain , the scope is to ensure that all variables and functions can be accessed in an orderly manner.

The following code shows when we use a variable in a function, if no amount of change in the current environment, it will search for a level down from the current scope chain environment, until the search so far. Less than a search, then it will generate an error.

var inputname="bigboss";
function Changename() {
    if (inputname=="bobo") {
        inputname="bigboss";
    }else {
        inputname="bobo";
    }
}
Changename();
console.log(inputname);//bobo

When we in the if statement to define variables or in the for statement defined variables are variables exist in the global environment.

if (true) {
    var currentvalue=10;
}
console.log(currentvalue);//10
for (var oo = 0; oo < 15; oo++) {
    //dosomething
}
console.log(oo);//15

Memory Management

After the definition and use of reference variables, if the data is no longer visible using the data set to null, to dereference .

Guess you like

Origin www.cnblogs.com/bigbosscyb/p/12102000.html