A local variable can have the same name as a global variable, but it is entirely separate; changing the value of one variable has no effect on the other. Only the local version has meaning inside the function in which it is declared.

 
// Global definition of aCentaur.
var aCentaur = "a horse with rider,";

// A local aCentaur variable is declared in this function.
function antiquities(){

   var aCentaur = "A centaur is probably a mounted Scythian warrior";
}

antiquities();
aCentaur += " as seen from a distance by a naive innocent.";

document.write(aCentaur);

// Output: "a horse with rider, as seen from a distance by a naive innocent."

In JavaScript variables are evaluated as if they were declared at the beginning of whatever scope they exist in. Sometimes this results in unexpected behaviors.

 
var aNumber = 100;
tweak();

function tweak(){

    // This prints "undefined", because aNumber is also defined locally below.
    document.write(aNumber);

    if (false)
    {
        var aNumber = 123;  
    }
}

When JavaScript executes a function, it first looks for all variable declarations, for example var someVariable;. It creates the variables with an initial value of undefined. If a variable is declared with a value, for example var someVariable = "something"; then it still initially has the value undefined, and takes on the declared value only when the line containing the declaration is executed.

JavaScript processes all variable declarations before executing any code, whether or not the declaration is inside a conditional block or other construct. Once JavaScript has found all the variables, it executes the code in the function. If a variable is implicitly declared inside a function - that is, if it appears on the left-hand-side of an assignment expression but has not been declared with var - then it is created as a global variable.

posted on 2013-06-17 18:02  @version  阅读(384)  评论(0)    收藏  举报