Page is a not externally linkable
- Code, Content, and Presentation
-- JavaScript and AJAX
---- How to Master JavaScript


fauxsoup - 9:18 pm on Oct 25, 2010 (gmt 0)


Important distinction on scope. When resolving a variable name, the script parser travels up the scope chain from the current point of execution to the window object (effectively global scope).

If you have a function foo inside of another function bar, any variables without explicit declaration will pass through bar before window. So:


var global = 1;
function foo() {
var global = 2;
function bar() {
anothervar = 1;
alert(global);
}
}


bar's reference to global will return 2, since that's the nearest explicitly declared variable in the scope chain matching that name.

Note, as well, that anothervar would be a global variable. Since there is no definition for anothervar, the parser travels up the scope chain until it hits the window object and, having found no corresponding definition, creates the variable there.

I suspect you know this, but it's a fact that's often glossed over. There's also all sorts of fun when passing around function references and trying to refer to "this"


Thread source:: http://www.webmasterworld.com/javascript/4216573.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com