<p><a href="http://www.stackoverflow.com/questions/61088/hidden-features-of-javascript#61118">Alan Storm's comments</a> in response to my answer regarding the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with" rel="noreferrer"><code>with</code> statement</a> 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 <code>with</code>, while avoiding its pitfalls.</p>

<p>Where have you found the <code>with</code> statement useful?</p>

[{'answer_id': 61566, 'author': 'Sören Kuklau', 'author_id': 1600, 'author_profile': 'https://Stackoverflow.com/users/1600', 'pm_score': 4, 'selected': False, 'text': "<p>Visual Basic.NET has a similar <code>With</code> statement. One of the more common ways I use it is to quickly set a number of properties. Instead of:</p>\n\n<pre><code>someObject.Foo = ''\nsomeObject.Bar = ''\nsomeObject.Baz = ''\n</code></pre>\n\n<p>, I can write:</p>\n\n<pre><code>With someObject\n    .Foo = ''\n    .Bar = ''\n    .Baz = ''\nEnd With\n</code></pre>\n\n<p>This isn't just a matter of laziness. It also makes for much more readable code. And unlike JavaScript, it does not suffer from ambiguity, as you have to prefix everything affected by the statement with a <code>.</code> (dot). So, the following two are clearly distinct:</p>\n\n<pre><code>With someObject\n    .Foo = ''\nEnd With\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>With someObject\n    Foo = ''\nEnd With\n</code></pre>\n\n<p>The former is <code>someObject.Foo</code>; the latter is <code>Foo</code> in the scope <em>outside</em> <code>someObject</code>.</p>\n\n<p>I find that JavaScript's lack of distinction makes it far less useful than Visual Basic's variant, as the risk of ambiguity is too high. Other than that, <code>with</code> is still a powerful idea that can make for better readability.</p>\n"}, {'answer_id': 61577, 'author': 'Sarien', 'author_id': 1994377, 'author_profile': 'https://Stackoverflow.com/users/1994377', 'pm_score': 3, 'selected': False, 'text': '<p>I think the obvious use is as a shortcut. If you\'re e.g. initializing an object you simply save typing a lot of "ObjectName." Kind of like lisp\'s "with-slots" which lets you write </p>\n\n<pre><code>(with-slots (foo bar) objectname\n   "some code that accesses foo and bar"\n</code></pre>\n\n<p>which is the same as writing</p>\n\n<pre><code>"some code that accesses (slot-value objectname \'foo) and (slot-value objectname \'bar)""\n</code></pre>\n\n<p>It\'s more obvious why this is a shortcut then when your language allows "Objectname.foo" but still.</p>\n'}, {'answer_id': 61582, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 3, 'selected': False, 'text': "<p>Having experience with Delphi, I would say that using <em>with</em> should be a last-resort size optimization, possibly performed by some kind of javascript minimizer algorithm with access to static code analysis to verify its safety.</p>\n\n<p>The scoping problems you can get into with liberal use of the <em>with</em> statement can be a royal pain in the a** and I wouldn't want anyone to experience a debugging session to figure out what the he.. is going on in your code, only to find out that it captured an object member or the wrong local variable, instead of your global or outer scope variable which you intended.</p>\n\n<p>The VB <em>with</em> statement is better, in that it needs the dots to disambiguate the scoping, but the Delphi <em>with</em> statement is a loaded gun with a hairtrigger, and it looks to me as though the javascript one is similar enough to warrant the same warning.</p>\n"}, {'answer_id': 61586, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 5, 'selected': False, 'text': '<p>You can define a small helper function to provide the benefits of <code>with</code> without the ambiguity:</p>\n\n<pre><code>var with_ = function (obj, func) { func (obj); };\n\nwith_ (object_name_here, function (_)\n{\n    _.a = "foo";\n    _.b = "bar";\n});\n</code></pre>\n'}, {'answer_id': 61595, 'author': '17 of 26', 'author_id': 2284, 'author_profile': 'https://Stackoverflow.com/users/2284', 'pm_score': 2, 'selected': False, 'text': '<p>I just really don\'t see how using the with is any more readable than just typing object.member.  I don\'t think it\'s any less readable, but I don\'t think it\'s any more readable either.</p>\n\n<p>Like lassevk said, I can definitely see how using with would be more error prone than just using the very explicit "object.member" syntax.</p>\n'}, {'answer_id': 61601, 'author': 'Svend', 'author_id': 2491, 'author_profile': 'https://Stackoverflow.com/users/2491', 'pm_score': 2, 'selected': False, 'text': "<p>Using with also makes your code slower in many implementation, as everything now gets wrapped in an extra scope for lookup. There's no legitimate reason for using with in JavaScript.</p>\n"}, {'answer_id': 61676, 'author': 'Alan Storm', 'author_id': 4668, 'author_profile': 'https://Stackoverflow.com/users/4668', 'pm_score': 6, 'selected': False, 'text': '<p>As my previous comments indicated, I don\'t think you can use <em><code>with</code></em> safely no matter how tempting it might be in any given situation. Since the issue isn\'t directly covered here, I\'ll repeat it.  Consider the following code</p>\n\n<pre><code>user = {};\nsomeFunctionThatDoesStuffToUser(user);\nsomeOtherFunction(user);\n\nwith(user){\n    name = \'Bob\';\n    age  = 20;\n}\n</code></pre>\n\n<p>Without carefully investigating those function calls, there\'s no way to tell what the state of your program will be after this code runs.  If <code>user.name</code> was already set, it will now be <code>Bob</code>. If it wasn\'t set, the global <code>name</code> will be initialized or changed to <code>Bob</code> and the <code>user</code> object will remain without a <code>name</code> property. </p>\n\n<p>Bugs happen.  If you use <em>with</em> you will eventually do this and increase the chances your program will fail.  Worse, you may encounter working code that sets a global in the with block, either deliberately or through the author not knowing about this quirk of the construct.  It\'s a lot like encountering fall through on a switch, you have no idea if the author intended this and there\'s no way to know if "fixing" the code will introduce a regression.</p>\n\n<p>Modern programming languages are chocked full of features. Some features, after years of use, are discovered to be bad, and should be avoided.  Javascript\'s <em><code>with</code></em> is one of them.</p>\n'}, {'answer_id': 61737, 'author': 'Allain Lalonde', 'author_id': 2443, 'author_profile': 'https://Stackoverflow.com/users/2443', 'pm_score': 5, 'selected': False, 'text': '<p>Hardly seems worth it since you can do the following:</p>\n\n<pre><code>var o = incrediblyLongObjectNameThatNoOneWouldUse;\no.name = "Bob";\no.age = "50";\n</code></pre>\n'}, {'answer_id': 62103, 'author': 'doekman', 'author_id': 56, 'author_profile': 'https://Stackoverflow.com/users/56', 'pm_score': 2, 'selected': False, 'text': '<p>I think the with-statement can come in handy when converting a template language into JavaScript. For example <a href="http://code.google.com/p/base2/source/browse/trunk/src/base2/JST/Interpreter.js" rel="nofollow noreferrer">JST</a> in <a href="http://code.google.com/p/base2/" rel="nofollow noreferrer">base2</a>, but I\'ve seen it more often. </p>\n\n<p>I agree one can program this without the with-statement. But because it doesn\'t give any problems it is a legitimate use. </p>\n'}, {'answer_id': 176406, 'author': 'Tom', 'author_id': 20, 'author_profile': 'https://Stackoverflow.com/users/20', 'pm_score': 2, 'selected': False, 'text': '<p>I think that the usefulness of <code>with</code> can be dependent on how well your code is written. For example, if you\'re writing code that appears like this:</p>\n\n<pre><code>var sHeader = object.data.header.toString();\nvar sContent = object.data.content.toString();\nvar sFooter = object.data.footer.toString();\n</code></pre>\n\n<p>then you could argue that <code>with</code> will improve the readability of the code by doing this:</p>\n\n<pre><code>var sHeader = null, sContent = null, sFooter = null;\nwith(object.data) {\n    sHeader = header.toString();\n    sContent = content.toString();\n    sFooter = content.toString();\n}\n</code></pre>\n\n<p>Conversely, it could be argued that you\'re violating the <a href="http://en.wikipedia.org/wiki/Law_of_Demeter" rel="nofollow noreferrer">Law of Demeter</a>, but, then again, maybe not. I digress =).</p>\n\n<p>Above all else, know that Douglas Crockford recommends <strong>not</strong> using <code>with</code>. I urge you to check out his blog post regarding <code>with</code> and its alternatives <a href="http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 185283, 'author': 'Shog9', 'author_id': 811, 'author_profile': 'https://Stackoverflow.com/users/811', 'pm_score': 9, 'selected': False, 'text': '<p>Another use occurred to me today, so I searched the web excitedly and found an existing mention of it: <a href="http://web.archive.org/web/20090111183416/http://www.hedgerwow.com/360/dhtml/js_block_scope.html" rel="noreferrer">Defining Variables inside Block Scope</a>.</p>\n<h3>Background</h3>\n<p>JavaScript, in spite of its superficial resemblance to C and C++, does not scope variables to the block they are defined in:</p>\n<pre><code>var name = &quot;Joe&quot;;\nif ( true )\n{\n   var name = &quot;Jack&quot;;\n}\n// name now contains &quot;Jack&quot;\n</code></pre>\n<p>Declaring a closure in a loop is a common task where this can lead to errors:</p>\n<pre><code>for (var i=0; i&lt;3; ++i)\n{\n   var num = i;\n   setTimeout(function() { alert(num); }, 10);\n}\n</code></pre>\n<p>Because the for loop does not introduce a new scope, the same <code>num</code> - with a value of <code>2</code> - will be shared by all three functions.</p>\n<h3>A new scope: <code>let</code> and <code>with</code></h3>\n<p>With the introduction of the <code>let</code> statement in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let" rel="noreferrer">ES6</a>, it becomes easy to introduce a new scope when necessary to avoid these problems:</p>\n<pre><code>// variables introduced in this statement \n// are scoped to each iteration of the loop\nfor (let i=0; i&lt;3; ++i)\n{\n   setTimeout(function() { alert(i); }, 10);\n}\n</code></pre>\n<p>Or even:</p>\n<pre><code>for (var i=0; i&lt;3; ++i)\n{\n   // variables introduced in this statement \n   // are scoped to the block containing it.\n   let num = i;\n   setTimeout(function() { alert(num); }, 10);\n}\n</code></pre>\n<p>Until ES6 is universally available, this use remains limited to the newest browsers and developers willing to use transpilers. However, we can easily simulate this behavior using <code>with</code>:</p>\n<pre><code>for (var i=0; i&lt;3; ++i)\n{\n   // object members introduced in this statement \n   // are scoped to the block following it.\n   with ({num: i})\n   {\n      setTimeout(function() { alert(num); }, 10);\n   }\n}\n</code></pre>\n<p>The loop now works as intended, creating three separate variables with values from 0 to 2. Note that variables declared <em>within</em> the block are not scoped to it, unlike the behavior of blocks in C++ (in C, variables must be declared at the start of a block, so in a way it is similar). This behavior is actually quite similar to a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#let_blocks" rel="noreferrer"><code>let</code> block syntax</a> introduced in earlier versions of Mozilla browsers, but not widely adopted elsewhere.</p>\n'}, {'answer_id': 1028684, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 6, 'selected': False, 'text': '<p>Yes, yes and yes.  There is a very legitimate use.  Watch:</p>\n\n<pre><code>with (document.getElementById("blah").style) {\n    background = "black";\n    color = "blue";\n    border = "1px solid green";\n}\n</code></pre>\n\n<p>Basically any other DOM or CSS hooks are fantastic uses of with.  It\'s not like "CloneNode" will be undefined and go back to the global scope unless you went out of your way and decided to make it possible.</p>\n\n<p>Crockford\'s speed complaint is that a new context is created by with.  Contexts are generally expensive.  I agree.  But if you just created a div and don\'t have some framework on hand for setting your css and need to set up 15 or so CSS properties by hand, then creating a context will probably be cheaper then variable creation and 15 dereferences:</p>\n\n<pre><code>var element = document.createElement("div"),\n    elementStyle = element.style;\n\nelementStyle.fontWeight = "bold";\nelementStyle.fontSize = "1.5em";\nelementStyle.color = "#55d";\nelementStyle.marginLeft = "2px";\n</code></pre>\n\n<p>etc...</p>\n'}, {'answer_id': 1462102, 'author': 'airportyh', 'author_id': 5304, 'author_profile': 'https://Stackoverflow.com/users/5304', 'pm_score': 7, 'selected': False, 'text': "<p>I have been using the with statement as a simple form of scoped import. Let's say you have a markup builder of some sort. Rather than writing:</p>\n\n<pre><code>markupbuilder.div(\n  markupbuilder.p('Hi! I am a paragraph!',\n    markupbuilder.span('I am a span inside a paragraph')\n  )\n)\n</code></pre>\n\n<p>You could instead write:</p>\n\n<pre><code>with(markupbuilder){\n  div(\n    p('Hi! I am a paragraph!',\n      span('I am a span inside a paragraph')\n    )\n  )\n}\n</code></pre>\n\n<p>For this use case, I am not doing any assignment, so I don't have the ambiguity problem associated with that.</p>\n"}, {'answer_id': 1463937, 'author': 'kangax', 'author_id': 130652, 'author_profile': 'https://Stackoverflow.com/users/130652', 'pm_score': 4, 'selected': False, 'text': "<p>I don't ever use with, don't see a reason to, and don't recommend it.</p>\n\n<p>The problem with <code>with</code> is that it <strong>prevents numerous lexical optimizations</strong> an ECMAScript implementation can perform. Given the rise of fast JIT-based engines, this issue will probably become even more important in the near future.</p>\n\n<p>It might look like <code>with</code> allows for cleaner constructs (when, say, introducing a new scope instead of a common anonymous function wrapper or replacing verbose aliasing), but it's  <strong>really not worth it</strong>. Besides a decreased performance, there's always a danger of assigning to a property of a wrong object (when property is not found on an object in injected scope) and perhaps erroneously introducing global variables. IIRC, latter issue is the one that motivated Crockford to recommend to avoid <code>with</code>.</p>\n"}, {'answer_id': 2207355, 'author': 'alex', 'author_id': 267082, 'author_profile': 'https://Stackoverflow.com/users/267082', 'pm_score': 2, 'selected': False, 'text': '<p>The with statement can be used to decrease the code size or for private class members, example:</p>\n\n<pre><code>// demo class framework\nvar Class= function(name, o) {\n   var c=function(){};\n   if( o.hasOwnProperty("constructor") ) {\n       c= o.constructor;\n   }\n   delete o["constructor"];\n   delete o["prototype"];\n   c.prototype= {};\n   for( var k in o ) c.prototype[k]= o[k];\n   c.scope= Class.scope;\n   c.scope.Class= c;\n   c.Name= name;\n   return c;\n}\nClass.newScope= function() {\n    Class.scope= {};\n    Class.scope.Scope= Class.scope;\n    return Class.scope;\n}\n\n// create a new class\nwith( Class.newScope() ) {\n   window.Foo= Class("Foo",{\n      test: function() {\n          alert( Class.Name );\n      }\n   });\n}\n(new Foo()).test();\n</code></pre>\n\n<p>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..</p>\n\n<p>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:</p>\n\n<pre><code>var o={x: 5},r, fnRAW= function(a,b){ return a*b; }, fnScoped, s, e, i;\nwith( o ) {\n    fnScoped= function(a,b){ return a*b; };\n}\n\ns= Date.now();\nr= 0;\nfor( i=0; i &lt; 1000000; i++ ) {\n    r+= fnRAW(i,i);\n}\ne= Date.now();\nconsole.log( (e-s)+"ms" );\n\ns= Date.now();\nr= 0;\nfor( i=0; i &lt; 1000000; i++ ) {\n    r+= fnScoped(i,i);\n}\ne= Date.now();\nconsole.log( (e-s)+"ms" );\n</code></pre>\n\n<p>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.</p>\n'}, {'answer_id': 2573547, 'author': 'aredridel', 'author_id': 306320, 'author_profile': 'https://Stackoverflow.com/users/306320', 'pm_score': 2, 'selected': False, 'text': '<p>It\'s good for putting code that runs in a relatively complicated environment into a container: I use it to make a local binding for "window" and such to run code meant for a web browser.</p>\n'}, {'answer_id': 2602245, 'author': 'Fire Crow', 'author_id': 80479, 'author_profile': 'https://Stackoverflow.com/users/80479', 'pm_score': 2, 'selected': False, 'text': '<p>I think the object literal use is interesting, like a drop-in replacement for using a closure</p>\n\n<pre><code>for(var i = nodes.length; i--;)\n{\n       // info is namespaced in a closure the click handler can access!\n       (function(info)\n       {           \n            nodes[i].onclick = function(){ showStuff(info) };\n       })(data[i]);\n}\n</code></pre>\n\n<p>or the with statement equivilent of a closure</p>\n\n<pre><code>for(var i = nodes.length; i--;)\n{\n       // info is namespaced in a closure the click handler can access!\n       with({info: data[i]})\n       {           \n            nodes[i].onclick = function(){ showStuff(info) };\n       }        \n}\n</code></pre>\n\n<p>I think the real risk is accidently minipulating variables that are not part of the with statement, which is why I like the object literal being passed into with, you can see exactly what it will be in the added context in the code.</p>\n'}, {'answer_id': 3122593, 'author': 'Jonah', 'author_id': 376785, 'author_profile': 'https://Stackoverflow.com/users/376785', 'pm_score': 3, 'selected': False, 'text': '<p>Using "with" can make your code more dry.</p>\n\n<p>Consider the following code:</p>\n\n<pre><code>var photo = document.getElementById(\'photo\');\nphoto.style.position = \'absolute\';\nphoto.style.left = \'10px\';\nphoto.style.top = \'10px\';\n</code></pre>\n\n<p>You can dry it to the following:</p>\n\n<pre><code>with(document.getElementById(\'photo\').style) {\n  position = \'absolute\';\n  left = \'10px\';\n  top = \'10px\';\n}\n</code></pre>\n\n<p>I guess it depends whether you have a preference for legibility or expressiveness. </p>\n\n<p>The first example is more legible and probably recommended for most code. But most code is pretty tame anyway. The second one is a bit more obscure but uses the expressive nature of the language to cut down on code size and superfluous variables.</p>\n\n<p>I imagine people who like Java or C# would choose the first way (object.member) and those who prefer Ruby or Python would choose the latter.</p>\n'}, {'answer_id': 3471239, 'author': 'palswim', 'author_id': 393280, 'author_profile': 'https://Stackoverflow.com/users/393280', 'pm_score': 2, 'selected': False, 'text': '<p>I created a "merge" function which eliminates some of this ambiguity with the <code>with</code> statement:</p>\n\n<pre><code>if (typeof Object.merge !== \'function\') {\n    Object.merge = function (o1, o2) { // Function to merge all of the properties from one object into another\n        for(var i in o2) { o1[i] = o2[i]; }\n        return o1;\n    };\n}\n</code></pre>\n\n<p>I can use it similarly to <code>with</code>, but I can know it won\'t affect any scope which I don\'t intend for it to affect.</p>\n\n<p>Usage:</p>\n\n<pre><code>var eDiv = document.createElement("div");\nvar eHeader = Object.merge(eDiv.cloneNode(false), {className: "header", onclick: function(){ alert("Click!"); }});\nfunction NewObj() {\n    Object.merge(this, {size: 4096, initDate: new Date()});\n}\n</code></pre>\n'}, {'answer_id': 3637640, 'author': 'Jordão', 'author_id': 31158, 'author_profile': 'https://Stackoverflow.com/users/31158', 'pm_score': 3, 'selected': False, 'text': '<p>You can use <code>with</code> to introduce the contents of an object as local variables to a block, like it\'s being done with this <a href="http://ejohn.org/blog/javascript-micro-templating/" rel="noreferrer">small template engine</a>.</p>\n'}, {'answer_id': 3666255, 'author': 'Elvis Salaris', 'author_id': 442248, 'author_profile': 'https://Stackoverflow.com/users/442248', 'pm_score': 1, 'selected': False, 'text': '<p>You got to see the validation of a form in javascript at W3schools <a href="http://www.w3schools.com/js/js_form_validation.asp" rel="nofollow noreferrer">http://www.w3schools.com/js/js_form_validation.asp</a> where the object form is "scanned" through to find an input with name \'email\'</p>\n\n<p>But i\'ve modified it to get from ANY form all the fields validate as not empty, regardless of the name or quantity of field in a form. Well i\'ve tested only text-fields.</p>\n\n<p>But the with() made things simpler. Here\'s the code:</p>\n\n<pre><code>function validate_required(field)\n{\nwith (field)\n  {\n  if (value==null||value=="")\n    {\n    alert(\'All fields are mandtory\');return false;\n    }\n  else\n    {\n    return true;\n    }\n  }\n}\n\nfunction validate_form(thisform)\n{\nwith (thisform)\n  {\n    for(fiie in elements){\n        if (validate_required(elements[fiie])==false){\n            elements[fiie].focus();\n            elements[fiie].style.border=\'1px solid red\';\n            return false;\n        } else {elements[fiie].style.border=\'1px solid #7F9DB9\';}\n    }\n\n  }\n  return false;\n}\n</code></pre>\n'}, {'answer_id': 3976785, 'author': 'Andy E', 'author_id': 94197, 'author_profile': 'https://Stackoverflow.com/users/94197', 'pm_score': 6, 'selected': False, 'text': '<p>I actually found the <code>with</code> 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 <a href="https://stackoverflow.com/questions/61552/are-there-legitimate-uses-for-javascripts-with-statement/185283#185283">Shog9\'s excellent answer</a>.</p>\n\n<p>To achieve this effect, I used two with statements to "layer" a scope behind the global scope:</p>\n\n<pre><code>with (consoleCommands) {\n    with (window) {\n        eval(expression); \n    }\n}\n</code></pre>\n\n<p>The great thing about this technique is that, aside from the performance disadvantages, it doesn\'t suffer the usual fears of the <code>with</code> statement, because we\'re evaluating in the global scope anyway - there\'s no danger of variables outside our pseudo-scope from being modified.  </p>\n\n<p>I was inspired to post this answer when, to my surprise, I managed to find the same technique used elsewhere - the <a href="https://chromium.googlesource.com/chromium/blink/+/791be071ca6682c629942f3e19c24cf997582a97/WebCore/inspector/front-end/InjectedScript.js#545" rel="noreferrer">Chromium source code</a>!</p>\n\n<pre><code>InjectedScript._evaluateOn = function(evalFunction, object, expression) {\n    InjectedScript._ensureCommandLineAPIInstalled();\n    // Surround the expression in with statements to inject our command line API so that\n    // the window object properties still take more precedent than our API functions.\n    expression = "with (window._inspectorCommandLineAPI) { with (window) { " + expression + " } }";\n    return evalFunction.call(object, expression);\n}\n</code></pre>\n\n<p><strong>EDIT:</strong> Just checked the Firebug source, they <a href="http://code.google.com/p/fbug/source/browse/branches/eval/content/firebug/commandLine.js#16" rel="noreferrer">chain 4 with statements together</a> for even more layers.  Crazy!</p>\n\n<pre><code>const evalScript = "with (__win__.__scope__.vars) { with (__win__.__scope__.api) { with (__win__.__scope__.userVars) { with (__win__) {" +\n    "try {" +\n        "__win__.__scope__.callback(eval(__win__.__scope__.expr));" +\n    "} catch (exc) {" +\n        "__win__.__scope__.callback(exc, true);" +\n    "}" +\n"}}}}";\n</code></pre>\n'}, {'answer_id': 6360857, 'author': 'Trevor Burnham', 'author_id': 66226, 'author_profile': 'https://Stackoverflow.com/users/66226', 'pm_score': 1, 'selected': False, 'text': '<p>CoffeeScript\'s <a href="http://github.com/satyr/coco" rel="nofollow">Coco</a> fork has a <code>with</code> keyword, but it simply sets <code>this</code> (also writable as <code>@</code> in CoffeeScript/Coco) to the target object within the block. This removes ambiguity and achieves ES5 strict mode compliance:</p>\n\n<pre><code>with long.object.reference\n  @a = \'foo\'\n  bar = @b\n</code></pre>\n'}, {'answer_id': 10077345, 'author': 'rplantiko', 'author_id': 1092785, 'author_profile': 'https://Stackoverflow.com/users/1092785', 'pm_score': 2, 'selected': False, 'text': '<p>For some short code pieces, I would like to use the trigonometric functions like <code>sin</code>, <code>cos</code> etc. in degree mode instead of in radiant mode. For this purpose, I use an <code>AngularDegree</code>object: </p>\n\n<pre class="lang-js prettyprint-override"><code>AngularDegree = new function() {\nthis.CONV = Math.PI / 180;\nthis.sin = function(x) { return Math.sin( x * this.CONV ) };\nthis.cos = function(x) { return Math.cos( x * this.CONV ) };\nthis.tan = function(x) { return Math.tan( x * this.CONV ) };\nthis.asin = function(x) { return Math.asin( x ) / this.CONV };\nthis.acos = function(x) { return Math.acos( x ) / this.CONV };\nthis.atan = function(x) { return Math.atan( x ) / this.CONV };\nthis.atan2 = function(x,y) { return Math.atan2(x,y) / this.CONV };\n};\n</code></pre>\n\n<p>Then I can use the trigonometric functions in degree mode without further language noise in a <code>with</code> block: </p>\n\n<pre><code>function getAzimut(pol,pos) {\n  ...\n  var d = pos.lon - pol.lon;\n  with(AngularDegree) {\n    var z = atan2( sin(d), cos(pol.lat)*tan(pos.lat) - sin(pol.lat)*cos(d) );\n    return z;\n    }\n  }\n</code></pre>\n\n<p>This means: I use an object as a collection of functions, which I enable in a limited code region for direct access. I find this useful.</p>\n'}, {'answer_id': 13052179, 'author': 'ianaz', 'author_id': 704916, 'author_profile': 'https://Stackoverflow.com/users/704916', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n\n<p><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/with" rel="noreferrer">Source: Mozilla.org</a></p>\n'}, {'answer_id': 14428133, 'author': 'avanderveen', 'author_id': 1472460, 'author_profile': 'https://Stackoverflow.com/users/1472460', 'pm_score': 0, 'selected': False, 'text': '<p>Here\'s a good use for <code>with</code>: adding new elements to an Object Literal, based on values stored in that Object.  Here\'s an example that I just used today:</p>\n\n<p>I had a set of possible tiles (with openings facing top, bottom, left, or right) that could be used, and I wanted a quick way of adding a list of tiles which would be always placed and locked at the start of the game.  I didn\'t want to keep typing <code>types.tbr</code> for each type in the list, so I just used <code>with</code>.</p>\n\n<pre><code>Tile.types = (function(t,l,b,r) {\n  function j(a) { return a.join(\' \'); }\n  // all possible types\n  var types = { \n    br:  j(  [b,r]),\n    lbr: j([l,b,r]),\n    lb:  j([l,b]  ),  \n    tbr: j([t,b,r]),\n    tbl: j([t,b,l]),\n    tlr: j([t,l,r]),\n    tr:  j([t,r]  ),  \n    tl:  j([t,l]  ),  \n    locked: []\n  };  \n  // store starting (base/locked) tiles in types.locked\n  with( types ) { locked = [ \n    br,  lbr, lbr, lb, \n    tbr, tbr, lbr, tbl,\n    tbr, tlr, tbl, tbl,\n    tr,  tlr, tlr, tl\n  ] } \n  return types;\n})("top","left","bottom","right");\n</code></pre>\n'}, {'answer_id': 19012662, 'author': 'Dexygen', 'author_id': 34806, 'author_profile': 'https://Stackoverflow.com/users/34806', 'pm_score': 0, 'selected': False, 'text': "<p>You can use <code>with</code> to avoid having to explicitly manage arity when using require.js:</p>\n<pre><code>var modules = requirejs.declare([{\n    'App' : 'app/app'\n}]);\n\nrequire(modules.paths(), function() { with (modules.resolve(arguments)) {\n    App.run();\n}});\n</code></pre>\n<p>Implementation of requirejs.declare:</p>\n<pre><code>requirejs.declare = function(dependencyPairs) {\n    var pair;\n    var dependencyKeys = [];\n    var dependencyValues = [];\n\n    for (var i=0, n=dependencyPairs.length; i&lt;n; i++) {\n        pair = dependencyPairs[i];\n        for (var key in dependencyPairs[i]) {\n            dependencyKeys.push(key);\n            dependencyValues.push(pair[key]);\n            break;\n        }\n    };\n\n    return {\n        paths : function() {\n            return dependencyValues;\n        },\n    \n        resolve : function(args) {\n            var modules = {};\n            for (var i=0, n=args.length; i&lt;n; i++) {\n                modules[dependencyKeys[i]] = args[i];\n            }\n            return modules;\n        }\n    }   \n}\n</code></pre>\n"}, {'answer_id': 23285657, 'author': 'Jackson', 'author_id': 1468130, 'author_profile': 'https://Stackoverflow.com/users/1468130', 'pm_score': 0, 'selected': False, 'text': '<p>As Andy E pointed out in the comments of Shog9\'s answer, this potentially-unexpected behavior occurs when using <code>with</code> with an object literal:</p>\n\n<pre><code>for (var i = 0; i &lt; 3; i++) {\n  function toString() {\n    return \'a\';\n  }\n  with ({num: i}) {\n    setTimeout(function() { console.log(num); }, 10);\n    console.log(toString()); // prints "[object Object]"\n  }\n}\n</code></pre>\n\n<p>Not that unexpected behavior wasn\'t <em>already</em> a hallmark of <code>with</code>.</p>\n\n<p>If you really still want to use this technique, at least use an object with a null prototype.</p>\n\n<pre><code>function scope(o) {\n  var ret = Object.create(null);\n  if (typeof o !== \'object\') return ret;\n  Object.keys(o).forEach(function (key) {\n    ret[key] = o[key];\n  });\n  return ret;\n}\n\nfor (var i = 0; i &lt; 3; i++) {\n  function toString() {\n    return \'a\';\n  }\n  with (scope({num: i})) {\n    setTimeout(function() { console.log(num); }, 10);\n    console.log(toString()); // prints "a"\n  }\n}\n</code></pre>\n\n<p>But this will only work in ES5+. Also don\'t use <code>with</code>.</p>\n'}, {'answer_id': 26707742, 'author': 'kevin.groat', 'author_id': 2939688, 'author_profile': 'https://Stackoverflow.com/users/2939688', 'pm_score': 0, 'selected': False, 'text': '<p>I am working on a project that will allow users to upload code in order to modify the behavior of parts of the application.  In this scenario, I have been using a <code>with</code> clause to keep their code from modifying anything outside of the scope that I want them to mess around with.  The (simplified) portion of code I use to do this is:</p>\n\n<pre><code>// this code is only executed once\nvar localScope = {\n    build: undefined,\n\n    // this is where all of the values I want to hide go; the list is rather long\n    window: undefined,\n    console: undefined,\n    ...\n};\nwith(localScope) {\n    build = function(userCode) {\n        eval(\'var builtFunction = function(options) {\' + userCode + \'}\');\n        return builtFunction;\n    }\n}\nvar build = localScope.build;\ndelete localScope.build;\n\n// this is how I use the build method\nvar userCode = \'return "Hello, World!";\';\nvar userFunction = build(userCode);\n</code></pre>\n\n<p>This code ensures (somewhat) that the user-defined code neither has access to any globally-scoped objects such as <code>window</code> nor to any of my local variables through a closure.</p>\n\n<p>Just as a word to the wise, I still have to perform static code checks on the user-submitted code to ensure they aren\'t using other sneaky manners to access global scope.  For instance, the following user-defined code grabs direct access to <code>window</code>:</p>\n\n<pre><code>test = function() {\n     return this.window\n};\nreturn test();\n</code></pre>\n'}, {'answer_id': 29690322, 'author': 'user2782001', 'author_id': 2782001, 'author_profile': 'https://Stackoverflow.com/users/2782001', 'pm_score': -1, 'selected': False, 'text': '<p>Just wanted to add you can get "with()" functionality with pretty syntax and no ambiguity with your own clever method...</p>\n\n<pre><code>     //utility function\n  function _with(context){\n           var ctx=context;\n           this.set=function(obj){\n             for(x in obj){\n                //should add hasOwnProperty(x) here\n                ctx[x]=obj[x];\n             }\n       } \n\n       return this.set;          \n }\n\n //how calling it would look in code...\n\n  _with(Hemisphere.Continent.Nation.Language.Dialect.Alphabet)({\n\n      a:"letter a",\n      b:"letter b",\n      c:"letter c",\n      d:"letter a",\n      e:"letter b",\n      f:"letter c",\n     // continue through whole alphabet...\n\n  });//look how readable I am!!!!\n</code></pre>\n\n<p>..or if you <em>really</em> want to use "with()" without ambiguity and no custom method, wrap it in an anonymous function and use .call </p>\n\n<pre><code>//imagine a deeply nested object \n//Hemisphere.Continent.Nation.Language.Dialect.Alphabet\n(function(){\n     with(Hemisphere.Continent.Nation.Language.Dialect.Alphabet){ \n         this.a="letter a";\n         this.b="letter b";\n         this.c="letter c";\n         this.d="letter a";\n         this.e="letter b";\n         this.f="letter c";\n         // continue through whole alphabet...\n     }\n}).call(Hemisphere.Continent.Nation.Language.Dialect.Alphabet)\n</code></pre>\n\n<p>However as others have pointed out, its somewhat pointless since you can do...</p>\n\n<pre><code> //imagine a deeply nested object Hemisphere.Continent.Nation.Language.Dialect.Alphabet\n     var ltr=Hemisphere.Continent.Nation.Language.Dialect.Alphabet \n     ltr.a="letter a";\n     ltr.b="letter b";\n     ltr.c="letter c";\n     ltr.d="letter a";\n     ltr.e="letter b";\n     ltr.f="letter c";\n     // continue through whole alphabet...\n</code></pre>\n'}, {'answer_id': 37640530, 'author': 'Little Alien', 'author_id': 6267925, 'author_profile': 'https://Stackoverflow.com/users/6267925', 'pm_score': 1, 'selected': False, 'text': '<p>My </p>\n\n<pre><code>switch(e.type) {\n    case gapi.drive.realtime.ErrorType.TOKEN_REFRESH_REQUIRED: blah\n    case gapi.drive.realtime.ErrorType.CLIENT_ERROR: blah\n    case gapi.drive.realtime.ErrorType.NOT_FOUND: blah\n}\n</code></pre>\n\n<p>boils down to</p>\n\n<pre><code>with(gapi.drive.realtime.ErrorType) {switch(e.type) {\n    case TOKEN_REFRESH_REQUIRED: blah\n    case CLIENT_ERROR: blah\n    case NOT_FOUND: blah\n}}\n</code></pre>\n\n<p>Can you trust so low-quality code? No, we see that it was made absolutely unreadable. This example undeniably proves that there is no need for with-statement, if I am taking readability right ;)</p>\n'}, {'answer_id': 65077825, 'author': 'shabaany', 'author_id': 12220097, 'author_profile': 'https://Stackoverflow.com/users/12220097', 'pm_score': 1, 'selected': False, 'text': '<p><strong>using &quot;with&quot; statement with proxy objects</strong></p>\n<p>I recently want to write a plugin for <a href="https://babeljs.io/" rel="nofollow noreferrer">babel</a> that enables macros. I would like to have a separate variable namespace that keeps my macro variables, and I can run my macro codes in that space. Also, I want to detect new variables that are defined in the macro codes(Because they are new macros).</p>\n<p>First, I choose the <a href="https://nodejs.org/api/vm.html" rel="nofollow noreferrer">vm</a> module, but I found global variables in the vm module like Array, Object, etc. are different from the main program, and I cant implement <code>module</code> and <code>require</code> that be fully compatible with that global objects(Because I cant reconstruct the core modules). In the end, I find the &quot;with&quot; statement.</p>\n<pre><code>const runInContext = function(code, context) {\n    context.global = context;\n    const proxyOfContext = new Proxy(context, { has: () =&gt; true });\n    let run = new Function(\n        &quot;proxyOfContext&quot;,\n        `\n            with(proxyOfContext){\n                with(global){\n                        ${code}\n                }\n            }\n        `\n    );\n    return run(proxyOfContext);\n};\n</code></pre>\n<p>This proxy object traps search of all variables and says: &quot;yes, I have that variable.&quot; and If the proxy object doesn\'t really have that variable, show its value as <code>undefined</code>.</p>\n<p>In this way, if any variable is defined in the macro <code>code</code> with the <code>var</code> statement, I can find it in the context object(like the vm module). But variables that are defined with <code>let</code> or <code>const</code> only available in that time and will not be saved in the context object(the vm module saves them but doesn\'t expose them).</p>\n<p><strong>Performance</strong>: Performance of this method is better than <code>vm.runInContext</code>.</p>\n<p><strong>safety</strong>: If you want to run code in a sandbox, this is not safe in any way, and you must use the vm module. It only provides a new namespace.</p>\n'}, {'answer_id': 73360501, 'author': 'nzn', 'author_id': 932256, 'author_profile': 'https://Stackoverflow.com/users/932256', 'pm_score': 0, 'selected': False, 'text': "<p><code>with</code> is useful coupled with shorthand object notation when you need to transform object structures from flat to hierarchical. So if you have:</p>\n<pre><code>var a = {id: 123, name: 'abc', attr1: 'efg', attr2: 'zxvc', attr3: '4321'};\n</code></pre>\n<p>So instead of:</p>\n<pre><code>var b = {\n    id: a.id,\n    name: a.name\n    metadata: {name: a.name, attr1: a.attr1}\n    extrastuff: {attr2: a.attr2, attr3: a.attr3}\n}\n</code></pre>\n<p>You can simply write:</p>\n<pre><code>with (a) {\n    var b = {\n        id,\n        name,\n        metadata: {name, attr1}\n        extrastuff: {attr2, attr3}\n    }\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/61552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/811/']