I preface this by saying I know that use of with
is highly discouraged, and I don't intend on using it either. I'm just curious about learning how it works (I'm trying to figure out scope in javascript).
If I have some code like this:
function foo(obj) {
with (obj) {
b = 2;
}
}
var o1 = {
a: "something"
};
foo( o1 );
console.log(o1.b) // This outputs undefined (makes sense)
console.log(b) // This outputs 2 (makes sense)
However, if I change foo to something like this:
function foo(obj) {
with (obj) {
var b = 2; // I use var b instead of b
}
}
When I pass in o1 to foo, again, o1 has no attribute b. Why is this? I thought using var
would declare b inside the scope of obj, so the attribute would be created inside o1 instead of in the global scope.