I am trying to understand JavaScript scope rules. What I read in textbooks and documentation is confused.
It seems to me that JavaScript is a static (or lexical) language with a scope - when trying to bind a variable name to a variable (definition), the lexical structure of the code is used.
The execution context seems similar to the stack stack in the call stack. Each execution context has a variable object on which all local variables (associated function) are defined. These variable objects are interconnected to provide a “scope chain” from the variable object at the top of the stack to the variable object at the bottom of the stack (window object). This chain of search scopes runs from top to bottom, binding variable names to variables. This is very similar to fixed coverage languages such as C / C ++ / Java.
It seems that there is one important difference with respect to C / C ++ / Java - it is possible to access a variable defined in a function whose stack stack is no longer in the call stack, as shown in the example below:
var color = "red";
var printColor;
function changeColor() {
var color = "green";
printColor = function(msg) {
alert(msg + color);
}
printColor("in changeColor context, color = ");
}
changeColor();
printColor("in global context, color = ");
Do I have this right? Are there any other issues I should be aware of?