JavaScript “with” statement – usages

I ran into the JavaScript with statement the other day, here are some examples of its usage:

Problem with variable scope and closures. In the below code, when the function runs, “i” will not be the same as the value it was when the function was created:

for(var i = 0; i < 3; ++i){
setTimeout(function() {
alert(i);
}, 100);
}

This doesn’t fix it either:

var num = 0;
for(var i = 0; i < 3; ++i){
num = i;

setTimeout(function() {
alert(num);
}, 100);
}

We can get our desired output using with


for(var i = 0; i < 3; ++i){
with({num: i}){
setTimeout(function() {
alert(num);
}, 100);
}
}

 

Note: I agree with this blog post about with considered harmfull. The above usage is different to this blog post.

Leave a Reply

Your email address will not be published. Required fields are marked *