Colectarea gunoiului in javascript

Garbage Collection

In languages like C and C++, memory must be freed manually.

The JavaScript interpreter is able to detect when an object will never again be used by the program. When it determines that an object is unreachable (i.e., there is no longer any way to refer to it using the variables in the program), it knows that the object is no longer needed and its memory can be reclaimed.

Garbage collection is automatic and is invisible to the programmer. You can create all the garbage objects you want, and the system will clean up after you!
 
http://docstore.mik.ua/orelly/webprog/jscript/ch04_05.htm 


Variables scope chain


When JavaScript code needs to look up the value of a variable x (a process called variable name resolution), it starts by looking at the first object in the chain. If that object has a property named x, the value of that property is used. If the first object does not have a property named x, JavaScript continues the search with the next object in the chain. If the second object does not have a property named x, the search moves on to the next object, and so on.



http://docstore.mik.ua/orelly/webprog/jscript/ch04_07.htm

Variabile In JavaScript

Exemple de variabile:
var i, sum;
for(var i = 0, j=10; i < 10; i++,j--) document.write(i*j, "
");

Observatii importante:
  • If you attempt to read the value of an undeclared variable, JavaScript will generate an error.
  • If you assign a value to a variable that you have not declared with var, JavaScript will implicitly declare that variable for you. Implicitly declared variables are always created as global variables, even if they are used within the body of a function. To prevent the creation of a global variable (or the use of an existing global variable) when you meant to create a local variable for use within a single function, you must always use the var statement within function bodies.:
Exemplu:
var scope = "global";         // Declare a global variable
function checkscope( ) {
    var scope = "local";      // Declare a local variable with the same name
    document.write(scope);    // Use the local variable, not the global one
}
checkscope( );               // Prints "local" 
  • All variables declared in a function, no matter where they are declared, are defined throughout the function.
Exemplu:
var scope = "global";
function f( ) {
    alert(scope);         // Displays "undefined", not "global"
    var scope = "local";  // Variable initialized here, but defined everywhere
    alert(scope);}         // Displays "local"}
f( ); 

The local variable is defined throughout the body of the function, which means the global variable by the same name is hidden throughout the function. Although the local variable is defined throughout, it is not actually initialized until the var statement is executed.

Cartea:
http://docstore.mik.ua/orelly/webprog/jscript/ch04_01.htm