Inside the with
block, the variable aptNum
is shadowed by address.aptNum
, and x
refers to the local variable (never address.x
, as there isn't such a property).
Considering that, and hoisting, your code is equivalent to:
var x = 90;
function test1(){
var aptNum; // hoisted
var x; // hoisted
var address = {
street: 'Haight',
aptNum: 2
};
with (address){
// any reference to aptNum or street inside the with block
// is actually referencing address.aptNum and address.street
alert(aptNum + ":" + x); // this outputs 2 : undefined.
// as expected, because there is no address.x
// and the local x is undefined at this point
aptNum = 100; // this assigns to address.aptNum
// the variable aptNum is shadowed by address.aptNum
x = 10; // this assigns to the local x inside the function
// (again because there is no address.x)
}
}