maybe it's stupid, feel depressed 'var' keyword. have trouble in figuring out following problems:
var local = true; function outer() { /* local scope */ var local = false; function inner() { alert(local); var local; } inner(); } outer(); function a(x) { return x * 2; } var a; alert(a);
any explanations appreciated.
annotated source; i'm assuming code starts out @ global scope:
var local = true; // creates global variable called `local` function outer() { /* local scope */ var local = false; // creates local `local` within `outer`, shadowing (hiding) global function inner() { alert(local); // alerts "undefined", value of `inner`'s `local` var local; // creates local `local` within `inner`, shadowing (hiding) `outer`'s version } inner(); } outer(); function a(x) { // creates global function `a` return x * 2; } var a; // has no effect alert(a); // alerts function source (on engines have it)
there 3 things @ work in code above:
a declaration in nested scope shadows (hides) declaration in containing scope.
local
inouter
shadows global, ,local
ininner
shadowsouter
'slocal
.var
declarations processed when execution enters execution context, not appear in source code. they're said "hoisted" because moved (raised, hoisted) top of context in occur. (more: poor misunderstoodvar
) effect particularly noticeable withininner
function, becauselocal
being alerted 1inner
, not 1outer
(which why it'sundefined
), though declaration underneath alert.function declarations create symbol in scope in they're defined, in same symbol space
var
declarations do. (specifically, both create entries in binding object of lexical environment of execution context in occur.) if have function declaration ,var
same name (asa
@ end of code), there's conflict. wins? function declaration wins, because of order dictated §10.5 of specification, says function declarations occur beforevar
declarations, ,var
symbol that's defined doesn't override it.
Comments
Post a Comment