With
I want to find out how with
is working with populating objects.
We know that properties are spread as global variables:
var x = {hello: 'world'};
with(x){
console.log(hello);
}
But what if we create such properties dynamically?
var x = {hello: 'world'};
with(x){
console.log(hello);
x.prop1 = 'val1'
console.log(prop1);
}
Yep, it works. Checked that it works in this way since at least IE5, so this is a reliable pattern.
It looks like this mechanic is used for all code. It is just wrapped in with(window){ ... }
in browser (even in strict
mode.
Do not use
with
if you are not developing something like a template engine, because it causes complex bugs and unpredictable behavior.