yb wrote:
In rereading responses here (thanks Richard as well), it looks like the
variable declared with 'var' does become part of the scope chain but is
useful since we don't need to reference a call object in the scope
chain explicitly?
Declared variables are properties of the Variable Object of the execution
context. So they are part of the scope chain of this context. However,
for their declaration the scope chain is not used: it does not matter if
you have declared the same variable before, especially not if it was
declared before in an outer execution context. A VariableDeclara tion
always creates a new property of the Variable Object of the context and
recreates it if such a property existed already.
var x = 0;
this.y = 23;
window.alert([x, y]); // 0,23
function foo()
{
// despite x is a global variable (and you would expect it to yield 0),
// x refers to the local variable in this context that was declared
// (see below) but not yet defined at this line
window.alert([x, y]); // [undefined],23
(function() { window.alert([x, y]); })(); // [undefined],23
var x = 42;
window.alert([x, y]); // 42,23
(function() { window.alert([x, y]); })(); // 42,23
// only a VariableStateme nt;
// variable instantiation comes before execution
var x;
window.alert([x, y]); // 42,23
// The local y variable is accessed instead of the global property;
// x refers to the local variable of the outer context instead of
// the global variable
(function() { var y = 11; window.alert([x, y]); })(); // 42,11
// a VariableDeclara tion replaces the previous value,
// `this' refers to the caller which is the Global Object;
// since either it has no property named `undefined' or it has
// a property named `undefined' with the `undefined' value
// (the latter conforms to ECMAScript), x is assigned the
// `undefined' value either way (provided nobody changed the
// value of the property before)
var x = this.undefined;
// modifies (or creates) a global property using the scope chain
y = 0;
// "[undefined],0" because x refers to the local variable and y
// to the modified global property
window.alert([x, y]);
// "[undefined],[undefined]" because y is declared as a local variable
// in the inner context even though there is a global property with
// that identifier already
(function() { var y; window.alert([x, y]); })();
}
foo();
// the global property can be deleted
delete y;
// the global variable cannot be deleted (has the DontDelete attribute)
delete x;
window.alert([x, this.y]); // 0,[undefined]
window.alert([x, y]); // ReferenceError: y is not defined
HTH
PointedEars