Saturday, February 28, 2009

Manipulating scope with the Javascript "with" statement

The with statement in Javascript allows you to tack the scope from an expression into the current execution context. It's really similar to the VB With statement. Here's a simple example:

function showDivStyle(){

with($('my_div')) {
console.log(style.backgroundColor);
}
}
showDivStyle(); //logs the string "yellow" at this point.
It gets even more interesting when you combine it with a closure, as the scope is extended even more.
function showDivStyle(){
var myClosure;

with($('my_div')) {
myClosure = function() {
console.log(style.backgroundColor);
}
}

return myClosure;
}

theClosure = showDivStyle();
theClosure(); //logs the string "yellow" at this point.