Kevin Greer's Stuff
[ start | index | login ]
start > 2008-05-06 > 1

2008-05-06 #1

Created by kgr. Last edited by kgr, 9 days ago. Viewed 17 times. #1
[edit] [rdf]
labels
attachments

Javascript 'with' Statement *NOT* Considered Harmful

JavaScript guru Douglas Crockford >>considers the ‘with’ statement harmful.

His reasoning is that if you do something like this:

with (ooo.eee.oo.ah_ah.ting.tang.walla.walla) {
    bing = true;
    bang = true;
}

Then “there is no way that you can tell by looking at the code which bing and bang will get modified”.

He instead suggests doing something like this:

var o = ooo.eee.oo.ah_ah.ting.tang.walla.walla;
o.bing = true;
o.bang = true;

But this doesn’t limit the scope of the ‘o’ variable and doesn’t have a satisfying block-structure (well, if that’s the sort of thing that brings you satisfaction).

You might think that you could do something like this:

{
   var o = ooo.eee.oo.ah_ah.ting.tang.walla.walla;

o.bing = true; o.bang = true; } // ‘o’ is still defined here

, to limit the scope and introduce a block-structure. But in the Firefox JS implementation at least, this doesn’t actually do what you would expect. The ‘o’ variable is still defined after the end of the block.

So here’s my solution:

with ({o:ooo.eee.oo.ah_ah.ting.tang.walla.walla}) {
    o.bing = true;
    o.bang = true;
}

Or if you’re feeling a little more Smalltalk-ish:

with ({self:ooo.eee.oo.ah_ah.ting.tang.walla.walla}) {
    self.bing = true;
    self.bang = true;
}

Notice that rather than using the object directly, I've put it into a map so that I can give it an explicit name.

You can also use the same trick to define multiple variables; essentially using ‘with’ like you would use Lisp or Scheme’s ‘let’ statement.

with ({
   walla : ooo.eee.oo.ah_ah.ting.tang.walla.walla,
   wanka : ooo.eee.oo.ah_ah.ting.tank.walla.wanka
     })
{
    walla.bing = true;
    wanka.bang = true;
}

You’ve gotta love JS’s Object/Map duality.

no comments | post comment
peerbox.com | Copyright 2005-2006 Kevin G. R. Greer