Alan Storm's comments in response to my answer regarding the with
statement got me thinking. I've seldom found a reason to use this particular language feature, and had never given much thought to how it might cause trouble. Now, I'm curious as to how I might make effective use of with
, while avoiding its pitfalls.
Where have you found the with
statement useful?
You can define a small helper function to provide the benefits of
with
without the ambiguity:I actually found the
with
statement to be incredibly useful recently. This technique never really occurred to me until I started my current project - a command line console written in JavaScript. I was trying to emulate the Firebug/WebKit console APIs where special commands can be entered into the console but they don't override any variables in the global scope. I thought of this when trying to overcome a problem I mentioned in the comments to Shog9's excellent answer.To achieve this effect, I used two with statements to "layer" a scope behind the global scope:
The great thing about this technique is that, aside from the performance disadvantages, it doesn't suffer the usual fears of the
with
statement, because we're evaluating in the global scope anyway - there's no danger of variables outside our pseudo-scope from being modified.I was inspired to post this answer when, to my surprise, I managed to find the same technique used elsewhere - the Chromium source code!
EDIT: Just checked the Firebug source, they chain 4 with statements together for even more layers. Crazy!
Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.
Source: Mozilla.org
The with statement can be used to decrease the code size or for private class members, example:
The with-statement is very usefull if you want to modify the scope, what is necessary for having your own global scope that you can manipulate at runtime. You can put constants on it or certain helper functions often used like e.g. "toUpper", "toLower" or "isNumber", "clipNumber" aso..
About the bad performance I read that often: Scoping a function won't have any impact on the performance, in fact in my FF a scoped function runs faster then an unscoped:
So in the above mentioned way used the with-statement has no negative effect on performance, but a good one as it deceases the code size, what impacts the memory usage on mobile devices.
You can use with to avoid having to explicitly manage arity when using require.js:
Implementation of requirejs.declare:
I think the with-statement can come in handy when converting a template language into JavaScript. For example JST in base2, but I've seen it more often.
I agree one can program this without the with-statement. But because it doesn't give any problems it is a legitimate use.