On the javascript variable scope and memory (2)

1, no block-level scope

javascript is not block-level scope, which other programmers will be very painful in understanding js code. In many other languages, such as C, braces code block has its own scope

for example

if(true) {
    var name = "saber"
};
console.log(name)//saber

 

The above codes can be seen, the environment variable is determined if statement is defined where the global environment, and therefore determines if access to the outside can be variable

(1) declare variables

function the Add (num1, num2) {
     // var sum = num1 + num2; // NOTE: If the following sum = num1 + num2; Bank replaced then being given sum is not defined, because of the use defined var sum, resulting in this variable is added to the nearest local environment, i.e. the add function, and thus not the external access, the error will be defined 
    SUM = + num1 num2; // not used here var, when the function is completed, sum is added to the global environment, so the function to access an external 
    return SUM; 
} 
var Result = the Add (7,7 ); 
the console.log (SUM) // 14 
the console.log (Result) // 14

 

(2) query identifier

Do not talk nonsense, directly on the code interpreter:

var name = "saber";
function getName(){
    return name;
}
console.log(getName())//saber

 

GetName call functions will be introduced defined variable name. To determine the value of the name, the search will begin a two-step process. First search getName () object that contains a call to see if the name of the identifier. Well, not yet, keep looking at a variable object, Aha to the variable object of the global environment Ha, oh excluded find the definition of a variable name, ending.

Is simply start from the local environment: Start on the local environment → → → an environment on a global environment ... → → end.

How can people say that if I was inside the function to define, what happens, you see!

var name = "saber";
function getName(){
    var name = "archer";
    return name;
}
console.log(getName())//archer

 

The reason is simple, the local environment from the beginning of the query, the found, no matter what is behind, and the search stops.

2, garbage collection

js can automatically manage the recovery of memory, in particular the principle is very short answer:

 To identify those variables are no longer used, and to free up the memory.

3, memory management

Necessary data value is stored in the execution code, once the data is no longer useful, it is preferably set to null to release references - dereferenced

function getName(){
    var name = "saber";
    return name;
}
var person = getName()
console.log(person)//saber
person = null//解除引用

 

Dereference this value does not mean automatic recovery of share memory, the real effect is to make value out of the execution environment for next run the garbage collector when it is recovered

Guess you like

Origin www.cnblogs.com/SaberInoryKiss/p/11772404.html