Skip to content

Instantly share code, notes, and snippets.

@iampeterbanjo
Created May 5, 2011 22:07
Show Gist options
  • Save iampeterbanjo/958078 to your computer and use it in GitHub Desktop.
Save iampeterbanjo/958078 to your computer and use it in GitHub Desktop.
An example of using "with"
var table = {}, cloth = {};
table.clean = false;
cloth.clean = true;
// clean the table please
function wipeTable(cloth){
console.log("cleaning table");
if(cloth.clean){
table.clean = true;
cloth.clean = false;
}
console.log("table is clean");
console.log("is the cloth clean? " + cloth.clean);
}
wipeTable(cloth);
// the cloth is dirty, lets clean it
function cleanCloth(){
console.log("cleaning cloth");
with(cloth){
clean = true;
color = "white";
}
console.log("is the cloth clean? " + cloth.clean);
console.log("what colour is the cloth? " + cloth.colour);
}
cleanCloth();
@iampeterbanjo
Copy link
Author

It is sort of a quirk with JavaScript where the scope of an operation changes when you use “with”. As with a few things in programming it is not that they can’t be used but they are often used badly. In JavaScript we are accustomed to the scope of “global” and functions. So a variable used in one function can’t be accessed by another function, right? Well when you use "wit"h you’re in ANOTHER scope, the scope of the thing you’re using. Let me explain.

Imagine you create a wipe function. It takes a cloth object and wipes a table. After you wipe a dirty table the cloth sadly becomes dirty. (See gist)

You can run this code in a browser console to see the results. If you look at this simple program at the end the cloth is clean but it is not blue, what happened? We were supposed to be in the scope of the “cloth” object which is how we set its property to clean but something weird happened and we couldn’t set the cloth’s colour. Uh oh! We ran into problems because the colour property was undefined but JavaScript usually lets us define properties on the fly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment