<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JSPatterns.com</title>
	<atom:link href="http://www.jspatterns.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jspatterns.com</link>
	<description>Exploring common JavaScript patterns and anti-patterns</description>
	<lastBuildDate>Sat, 10 Sep 2011 09:15:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.3</generator>
		<item>
		<title>The ridiculous case of adding a script element</title>
		<link>http://www.jspatterns.com/the-ridiculous-case-of-adding-a-script-element/</link>
		<comments>http://www.jspatterns.com/the-ridiculous-case-of-adding-a-script-element/#comments</comments>
		<pubDate>Sat, 10 Sep 2011 09:15:52 +0000</pubDate>
		<dc:creator>stoyan</dc:creator>
				<category><![CDATA[DOM]]></category>

		<guid isPermaLink="false">http://www.jspatterns.com/?p=97</guid>
		<description><![CDATA[Adding a script element to a page should be a no-brainer. Yet, it's ridiculously unreliable in the wild - when you don't have any idea of the surrounding markup. You know the drill - create a script element, point its src to a URL and add it to the page so that script file can [...]]]></description>
			<content:encoded><![CDATA[<p>Adding a script element to a page should be a no-brainer. Yet, it's ridiculously unreliable in the wild - when you don't have any idea of the surrounding markup.</p>
<p>You know the drill - create a script element, point its src to a URL and add it to the page so that script file can be downloaded in a <a href="http://yuiblog.com/blog/2008/07/22/non-blocking-scripts/">non-blocking manner</a>.</p>
<p>Creating the script is nice and easy:</p>
<div class="hl-main">
<pre><span class="hl-reserved">var</span><span class="hl-code"> </span><span class="hl-identifier">js</span><span class="hl-code"> = </span><span class="hl-builtin">document</span><span class="hl-code">.</span><span class="hl-identifier">createElement</span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">script</span><span class="hl-quotes">'</span><span class="hl-brackets">)</span><span class="hl-code">;
</span><span class="hl-identifier">js</span><span class="hl-code">.</span><span class="hl-identifier">src</span><span class="hl-code"> = </span><span class="hl-quotes">'</span><span class="hl-string">myscript.js</span><span class="hl-quotes">'</span><span class="hl-code">;</span></pre>
</div>
<p>The problem is how to add it to the page.</p>
<h3>1. to the head</h3>
<p>Probably the most common approach is to append to the head of the document:</p>
<div class="hl-main">
<pre><span class="hl-builtin">document</span><span class="hl-code">.</span><span class="hl-identifier">getElementsByTagName</span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">head</span><span class="hl-quotes">'</span><span class="hl-brackets">)</span><span class="hl-brackets">[</span><span class="hl-number">0</span><span class="hl-brackets">]</span><span class="hl-code">.</span><span class="hl-identifier">appendChild</span><span class="hl-brackets">(</span><span class="hl-identifier">js</span><span class="hl-brackets">)</span><span class="hl-code">;</span></pre>
</div>
<p>You get all head elements (there should be only one) and you add the script there so the result is </p>
<div class="hl-main">
<pre><span class="hl-brackets">&lt;</span><span class="hl-reserved">html</span><span class="hl-brackets">&gt;</span><span class="hl-code">
  </span><span class="hl-brackets">&lt;</span><span class="hl-reserved">head</span><span class="hl-brackets">&gt;</span><span class="hl-code">
    </span><span class="hl-brackets">&lt;</span><span class="hl-reserved">script</span><span class="hl-brackets">&gt;</span><span class="hl-code">
    ...</span></pre>
</div>
<p>But what if there's no head in the document? Remember, we want solid robust code that always works.</p>
<p>Well turns out that most browsers will create the head element even if the <head> tag is not there.</p>
<p>Most, but not all as Steve Souders' <a href="http://stevesouders.com/tests/autohead.html">browserscope test shows</a>. Exceptions include browsers like Opera 8 but also Android 1.6 and one iPhone 3 - hardly old and negligible.</p>
<p><img src="http://www.jspatterns.com/wp-content/uploads/2011/09/autohead.png" alt="" title="autohead" width="449" height="513" class="alignnone size-full wp-image-99" /></p>
<p>So head is out.</p>
<h3>2. add to the body</h3>
<p>This is even shorter:</p>
<div class="hl-main">
<pre><span class="hl-builtin">document</span><span class="hl-code">.</span><span class="hl-identifier">body</span><span class="hl-code">.</span><span class="hl-identifier">appendChild</span><span class="hl-brackets">(</span><span class="hl-identifier">js</span><span class="hl-brackets">)</span><span class="hl-code">;</span></pre>
</div>
<p>what if there's no <code>&lt;body&gt;</code> tag? Well <a href="http://www.phpied.com/files/bscope/autobody.html">my test shows</a> that all tested browsers will create a body element. Even one that has a working <code>appendChild()</code> method. Now, while some of those that don't create head, do create body, I'm still a little uncomfortable that I couldn't find a single browser that doesn't create body. Makes me feel a little worried about the testing and data collecting.</p>
<p>But even if we assume that in all browsers, document.body always exist, there's still a problem. IE7 and the dreaded "Operation aborted" error.</p>
<p>If you modify BODY while loading the page and from a script that is not a direct child of body, but nested in another element, you get Operation aborted and nothing works.</p>
<p>Surprisingly simple page fails miserably:</p>
<div class="hl-main">
<pre><span class="hl-brackets">&lt;</span><span class="hl-reserved">html</span><span class="hl-brackets">&gt;</span><span class="hl-code">
  </span><span class="hl-brackets">&lt;</span><span class="hl-reserved">body</span><span class="hl-brackets">&gt;</span><span class="hl-code">
      </span><span class="hl-brackets">&lt;</span><span class="hl-reserved">div</span><span class="hl-brackets">&gt;</span><span class="hl-code">
          </span><span class="hl-brackets">&lt;</span><span class="hl-reserved">script</span><span class="hl-brackets">&gt;</span>
<span class="hl-code">          </span><span class="hl-reserved">var</span><span class="hl-code"> </span><span class="hl-identifier">js</span><span class="hl-code"> = </span><span class="hl-builtin">document</span><span class="hl-code">.</span><span class="hl-identifier">createElement</span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">script</span><span class="hl-quotes">'</span><span class="hl-brackets">)</span><span class="hl-code">;
          </span><span class="hl-identifier">js</span><span class="hl-code">.</span><span class="hl-identifier">async</span><span class="hl-code"> = </span><span class="hl-reserved">true</span><span class="hl-code">;
          </span><span class="hl-identifier">js</span><span class="hl-code">.</span><span class="hl-identifier">src</span><span class="hl-code"> = </span><span class="hl-quotes">&quot;</span><span class="hl-string">http://tools.w3clubs.com/pagr/1.sleep-2.js</span><span class="hl-quotes">&quot;</span><span class="hl-code">;
          </span><span class="hl-builtin">document</span><span class="hl-code">.</span><span class="hl-identifier">body</span><span class="hl-code">.</span><span class="hl-identifier">appendChild</span><span class="hl-brackets">(</span><span class="hl-identifier">js</span><span class="hl-brackets">)</span><span class="hl-code">;</span>
          <span class="hl-brackets">&lt;/</span><span class="hl-reserved">script</span><span class="hl-brackets">&gt;</span><span class="hl-code">
      </span><span class="hl-brackets">&lt;/</span><span class="hl-reserved">div</span><span class="hl-brackets">&gt;</span><span class="hl-code">
  </span><span class="hl-brackets">&lt;/</span><span class="hl-reserved">body</span><span class="hl-brackets">&gt;</span><span class="hl-code">
</span><span class="hl-brackets">&lt;/</span><span class="hl-reserved">html</span><span class="hl-brackets">&gt;</span></pre>
</div>
<p><a href="http://www.phpied.com/files/operation-aborted/oa-script-body.html">See it live in IE7</a> and be amazed</p>
<p><a href="http://www.jspatterns.com/wp-content/uploads/2011/09/ie7.png"><img src="http://www.jspatterns.com/wp-content/uploads/2011/09/ie7-300x218.png" alt="" title="ie7" width="300" height="218" class="alignnone size-medium wp-image-98" /></a></p>
<p>Now operation aborted <a href="http://www.jspatterns.com/defer-for-ie7s-operation-aborted-error/">may be solved with a <code>defer</code></a>, but <a href="https://github.com/paulirish/lazyweb-requests/issues/42#issuecomment-1901803">maybe not in IE9</a>.</p>
<p>Another reason not to attempt anything with body is if the script is included in the head. At execution time we have not reached <code>&lt;body&gt;</code> yet, so <code>document.body</code> doesn't exist. <a href="http://analytics.nfshost.com/nobody.html">Demo.</a></p>
<h3>3. use <code>documentElement</code></h3>
<p><code>document.documentElement</code> is the html doc itself. Now that's got to exist no matter what.</p>
<p>So you go like</p>
<div class="hl-main">
<pre><span class="hl-reserved">var</span><span class="hl-code"> </span><span class="hl-identifier">html</span><span class="hl-code"> = </span><span class="hl-builtin">document</span><span class="hl-code">.</span><span class="hl-identifier">documentElement</span><span class="hl-code">;
</span><span class="hl-identifier">html</span><span class="hl-code">.</span><span class="hl-identifier">insertBefore</span><span class="hl-brackets">(</span><span class="hl-identifier">js</span><span class="hl-code">, </span><span class="hl-identifier">html</span><span class="hl-code">.</span><span class="hl-identifier">firstChild</span><span class="hl-brackets">)</span><span class="hl-code">;</span></pre>
</div>
<p>And it works!</p>
<p>But what if the <code>firstChild</code> is a comment before the head? This makes something kinda weird:</p>
<div class="hl-main">
<pre><span class="hl-code">
</span><span class="hl-brackets">&lt;</span><span class="hl-reserved">html</span><span class="hl-brackets">&gt;</span><span class="hl-code">
  </span><span class="hl-brackets">&lt;</span><span class="hl-reserved">script</span><span class="hl-brackets">&gt;</span><span class="hl-code">
  </span><span class="hl-comment">&lt;!--</span><span class="hl-comment"> comment </span><span class="hl-comment">--&gt;</span><span class="hl-code">
  </span><span class="hl-brackets">&lt;</span><span class="hl-reserved">head</span><span class="hl-brackets">&gt;</span><span class="hl-code">
    ..</span></pre>
</div>
<p>Script obviously has no place there, but <a href="http://www.phpied.com/files/operation-aborted/documentelement.html">my test page</a> worked in ie6789, and recent versions of FF, Chrome, Safari, Opera.</p>
<p>But looks like there are other browsers where this comment thing fails <a href="http://www.stevesouders.com/blog/2010/05/11/appendchild-vs-insertbefore/#comment-2084">as reported</a>(btw, good to read the whole post and all the comments) by Google Analytics folks who say they have received complaints when they used to do that. There might be other cases or browsers I didn't try. So reluctantly, we move on.</p>
<h3>4. hook to the first <code>script</code></h3>
<p>Ahaa, if you're running a script, then this script must either be inline <span class="hl-brackets">&lt;</span><span class="hl-reserved">script</span><span class="hl-brackets">&gt;</span><span class="hl-code">bla</span><span class="hl-brackets">&lt;/</span><span class="hl-reserved">script</span><span class="hl-brackets">&gt;</span> or external <span class="hl-brackets">&lt;</span><span class="hl-reserved">script</span><span class="hl-code"> </span><span class="hl-var">src</span><span class="hl-code">=</span><span class="hl-quotes">&quot;</span><span class="hl-string">meh.js</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">&gt;</span>. Either way, there's gotta be at least one script tag! Wo-hoo! </p>
<p>So the final solution is:</p>
<div class="hl-main">
<pre><span class="hl-reserved">var</span><span class="hl-code"> </span><span class="hl-identifier">first</span><span class="hl-code"> = </span><span class="hl-builtin">document</span><span class="hl-code">.</span><span class="hl-identifier">getElementsByTagName</span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">script</span><span class="hl-quotes">'</span><span class="hl-brackets">)</span><span class="hl-brackets">[</span><span class="hl-number">0</span><span class="hl-brackets">]</span><span class="hl-code">;
</span><span class="hl-identifier">first</span><span class="hl-code">.</span><span class="hl-identifier">parentNode</span><span class="hl-code">.</span><span class="hl-identifier">insertBefore</span><span class="hl-brackets">(</span><span class="hl-identifier">js</span><span class="hl-code">, </span><span class="hl-identifier">first</span><span class="hl-brackets">)</span><span class="hl-code">;</span></pre>
</div>
<p>No matter where the first script might be, we glue out new one right above it.</p>
<p>Drawback is that looking for script nodes might be a little more expensive than looking for <code>document.documentElement</code> or <code>document.body</code> or the single match of <code>getElemenetsByTagName('head')</code></p>
<p>There's still a case when there might not be a script element at all. Ah, impossible, since we're running a script there must be a script element! Well (and thanks to <a href="http://perfectionkills.com">@kangax</a> who pointed this to me while he was reviewing <a href="http://www.amazon.com/dp/0596806752/?tag=w3clubs-20">JavaScript Patterns</a>!) here's one example:</p>
<div class="hl-main">
<pre><span class="hl-brackets">&lt;</span><span class="hl-reserved">body</span><span class="hl-code"> </span><span class="hl-var">onload</span><span class="hl-code">=</span><span class="hl-quotes">&quot;</span><span class="hl-string">alert('Look ma, executing script without a script tag!')</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">&gt;</span></pre>
</div>
<p>Overall while not completely foolproof, this is as close as you can get to being able to achieve the simple task - add a new script node. Isn't web development just magnificent? </p>
<p>(Funny thing if you use this only to load a script asynchronously: in order to load a script (file), you need a script that refers to a script, possibly itself. JavaScript all around.)</p>
<p>Once again the whole snippet:</p>
<div class="hl-main">
<pre><span class="hl-reserved">var</span><span class="hl-code"> </span><span class="hl-identifier">js</span><span class="hl-code"> = </span><span class="hl-builtin">document</span><span class="hl-code">.</span><span class="hl-identifier">createElement</span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">script</span><span class="hl-quotes">'</span><span class="hl-brackets">)</span><span class="hl-code">;
</span><span class="hl-identifier">js</span><span class="hl-code">.</span><span class="hl-identifier">src</span><span class="hl-code"> = </span><span class="hl-quotes">'</span><span class="hl-string">myscript.js</span><span class="hl-quotes">'</span><span class="hl-code">;
</span><span class="hl-reserved">var</span><span class="hl-code"> </span><span class="hl-identifier">first</span><span class="hl-code"> = </span><span class="hl-builtin">document</span><span class="hl-code">.</span><span class="hl-identifier">getElementsByTagName</span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">script</span><span class="hl-quotes">'</span><span class="hl-brackets">)</span><span class="hl-brackets">[</span><span class="hl-number">0</span><span class="hl-brackets">]</span><span class="hl-code">;
</span><span class="hl-identifier">first</span><span class="hl-code">.</span><span class="hl-identifier">parentNode</span><span class="hl-code">.</span><span class="hl-identifier">insertBefore</span><span class="hl-brackets">(</span><span class="hl-identifier">js</span><span class="hl-code">, </span><span class="hl-identifier">first</span><span class="hl-brackets">)</span><span class="hl-code">;</span></pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.jspatterns.com/the-ridiculous-case-of-adding-a-script-element/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>&#8220;defer&#8221; for IE7&#8242;s operation aborted error</title>
		<link>http://www.jspatterns.com/defer-for-ie7s-operation-aborted-error/</link>
		<comments>http://www.jspatterns.com/defer-for-ie7s-operation-aborted-error/#comments</comments>
		<pubDate>Fri, 09 Sep 2011 23:52:56 +0000</pubDate>
		<dc:creator>stoyan</dc:creator>
				<category><![CDATA[The Blog]]></category>

		<guid isPermaLink="false">http://www.jspatterns.com/?p=94</guid>
		<description><![CDATA[IE has this "operation aborted" problem (MSDN article) when you try to change your parent while it's not ready. This is the example they give that causes this error: &#60;html&#62; &#60;body&#62; &#60;div&#62; &#60;script&#62; document.body.innerHTML+=&#34;sample text&#34;; &#60;/script&#62; &#60;/div&#62; &#60;/body&#62; &#60;/html&#62; Turns out you can easily solve it by just adding a defer attribute to the script. [...]]]></description>
			<content:encoded><![CDATA[<p>IE has this "operation aborted" problem (<a href="http://support.microsoft.com/kb/927917">MSDN article</a>) when you try to change your parent while it's not ready.</p>
<p>This is the example they give that causes this error:</p>
<div class="hl-main">
<pre><span class="hl-brackets">&lt;</span><span class="hl-reserved">html</span><span class="hl-brackets">&gt;</span><span class="hl-code">
  </span><span class="hl-brackets">&lt;</span><span class="hl-reserved">body</span><span class="hl-brackets">&gt;</span><span class="hl-code">
    </span><span class="hl-brackets">&lt;</span><span class="hl-reserved">div</span><span class="hl-brackets">&gt;</span><span class="hl-code">
      </span><span class="hl-brackets">&lt;</span><span class="hl-reserved">script</span><span class="hl-brackets">&gt;</span>
<span class="hl-code">        </span><span class="hl-builtin">document</span><span class="hl-code">.</span><span class="hl-identifier">body</span><span class="hl-code">.</span><span class="hl-identifier">innerHTML</span><span class="hl-code">+=</span><span class="hl-quotes">&quot;</span><span class="hl-string">sample text</span><span class="hl-quotes">&quot;</span><span class="hl-code">;</span>
      <span class="hl-brackets">&lt;/</span><span class="hl-reserved">script</span><span class="hl-brackets">&gt;</span><span class="hl-code">
    </span><span class="hl-brackets">&lt;/</span><span class="hl-reserved">div</span><span class="hl-brackets">&gt;</span><span class="hl-code">
  </span><span class="hl-brackets">&lt;/</span><span class="hl-reserved">body</span><span class="hl-brackets">&gt;</span><span class="hl-code">
</span><span class="hl-brackets">&lt;/</span><span class="hl-reserved">html</span><span class="hl-brackets">&gt;</span></pre>
</div>
<p>Turns out you can easily solve it by just adding a <code>defer</code> attribute to the <code>script</code>. This works just fine:</p>
<div class="hl-main">
<pre><span class="hl-brackets">&lt;</span><span class="hl-reserved">html</span><span class="hl-brackets">&gt;</span><span class="hl-code">
  </span><span class="hl-brackets">&lt;</span><span class="hl-reserved">body</span><span class="hl-brackets">&gt;</span><span class="hl-code">
    </span><span class="hl-brackets">&lt;</span><span class="hl-reserved">div</span><span class="hl-brackets">&gt;</span><span class="hl-code">
      </span><span class="hl-brackets">&lt;</span><span class="hl-reserved">script</span> defer<span class="hl-brackets">&gt;</span>
<span class="hl-code">        </span><span class="hl-builtin">document</span><span class="hl-code">.</span><span class="hl-identifier">body</span><span class="hl-code">.</span><span class="hl-identifier">innerHTML</span><span class="hl-code">+=</span><span class="hl-quotes">&quot;</span><span class="hl-string">sample text</span><span class="hl-quotes">&quot;</span><span class="hl-code">;</span>
      <span class="hl-brackets">&lt;/</span><span class="hl-reserved">script</span><span class="hl-brackets">&gt;</span><span class="hl-code">
    </span><span class="hl-brackets">&lt;/</span><span class="hl-reserved">div</span><span class="hl-brackets">&gt;</span><span class="hl-code">
  </span><span class="hl-brackets">&lt;/</span><span class="hl-reserved">body</span><span class="hl-brackets">&gt;</span><span class="hl-code">
</span><span class="hl-brackets">&lt;/</span><span class="hl-reserved">html</span><span class="hl-brackets">&gt;</span></pre>
</div>
<p><a href="http://www.phpied.com/files/operation-aborted/oa.html">Demo page here</a></p>
<p>BTW, this operation aborted may bite you if you decide to append a script node to the body, like </p>
<pre>var js = document.createElement('script');
js.async = true;
js.src = "http://tools.w3clubs.com/pagr/1.sleep-2.js";
document.body.appendChild(js); </pre>
<p>So it's not a good idea to append to the body like this when you don't control the page you're adding this code to, although <code>document.body</code> <a href="http://www.phpied.com/files/bscope/autobody.html">seems to be always available</a> even when the page doesn't have a &lt;body&gt; tag</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jspatterns.com/defer-for-ie7s-operation-aborted-error/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Scripting Photoshop with JavaScript</title>
		<link>http://www.jspatterns.com/scripting-photoshop-with-javascript/</link>
		<comments>http://www.jspatterns.com/scripting-photoshop-with-javascript/#comments</comments>
		<pubDate>Sun, 21 Aug 2011 00:03:58 +0000</pubDate>
		<dc:creator>stoyan</dc:creator>
				<category><![CDATA[JS everywhere]]></category>

		<guid isPermaLink="false">http://www.jspatterns.com/?p=88</guid>
		<description><![CDATA[Did you know you can script common Photoshop tasks with JavaScript? Now you do IDE even When you install PS it comes with a tool called ExtendScript Toolkit, which is an IDE to write scripts - with debugger, console to try stuff out etc. To launch I just type "Extend" in Spotlight search. I'm guessing [...]]]></description>
			<content:encoded><![CDATA[<p>Did you know you can script common Photoshop tasks with JavaScript? Now you do <img src='http://www.jspatterns.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>IDE even</h2>
<p>When you install PS it comes with a tool called ExtendScript Toolkit, which is an IDE to write scripts - with debugger, console to try stuff out etc.</p>
<p>To launch I just type "Extend" in Spotlight search. I'm guessing it's got to be somewhere in Program Files\Adobe on Windows too.</p>
<p><img src="http://www.jspatterns.com/wp-content/uploads/2011/08/launch-extend.png" alt="" title="launch-extend" width="370" height="209" class="alignnone size-full wp-image-89" /></p>
<p>Here it is:</p>
<p><img src="http://www.jspatterns.com/wp-content/uploads/2011/08/extend-toolkit.png" alt="" title="extend-toolkit" width="650" class="alignnone size-full wp-image-90" /></p>
<h2>Getting started</h2>
<p>As you can see on the screenshot, it's easy to get started.</p>
<pre>
app; // the Photoshop application
app.documents; // collection of open files/documents
app.documents[0]; // the first file
app.documents[0].name; // the first file's filename
app.documents[0].layers.length // how many layers in the doc
</pre>
<h2>Running your script</h2>
<p>There's a green "play" button in the IDE, it runs your script.</p>
<p>The directive:</p>
<pre>#target photoshop</pre>
<p>tells the engine that this is a photoshop script. Apparently you can script other Adobe products too.</p>
<p>If you don't have photoshop open, this directive will open it for you. Then it's all you - open a file, hide a layer, save, close, etc</p>
<p>Also if you save your script file with a .jsx extension, you can put in on the desktop and double-click it. Easy as pie.</p>
<p>And finally, if you put it in the appropriate directory (PSDIR/Presets/Scripts), it will show up in Photoshop menus under File -> Scripts</p>
<h2>Docs</h2>
<p>A *Yahoo* search will find the docs for you right here:<br />
<a href="http://www.adobe.com/devnet/photoshop/scripting.html">http://www.adobe.com/devnet/photoshop/scripting.html</a></p>
<p>There's a scripting guide (nice) and a JavaScript reference (the exact object/method names).</p>
<p>There are also VBScript and AppleScript references in case you insist on writing non-portable scripts <img src='http://www.jspatterns.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>Generating code</h2>
<p>Getting started with a completely new API can be a little uphill-y walk. For me it was especially so when it comes to saving a file with all the options. Worry not, you can generate code too!</p>
<p>Check the scripting guide where it talks about "The ScriptListener Plug-In". It's a plugin that you already have, you just copy it to to the appropriate directory to activate it and then restart PS.</p>
<p>Then whatever you do in photoshop will generate code in a .log file on your desktop. Then you can go back and cleanup that file (it generates somewhat verbose code) and get the parts you need.</p>
<h2>Example - Mojotune chords</h2>
<p>So for this "JavaScript is Everywhere" talk I gave <a href="http://www.oscon.com/oscon2011/public/schedule/detail/18579">this year at OSCON</a> (<a href="http://www.slideshare.net/stoyan/javascript-is-everywhere">slides</a>) I came up (with a <a href="http://javorvatchkov.com">friend</a>'s help) with a sample application that I ported to different environments.</p>
<p>The core of it is m.js (m as in mojo, m as in (data) model). It's a portable piece of JavaScript that knows a lot about guitar chords. I wanted to generate nice PNGs with the data from the chord model. So - Photoshop scripting.</p>
<p>The document template is shown here with three visible layers.</p>
<p><img src="http://www.jspatterns.com/wp-content/uploads/2011/08/psd.png" alt="" title="psd" width="455" height="367" class="alignnone size-full wp-image-91" /></p>
<p>This is the guitar's neck and each dot is where you press. The template has a layer for each dot (each fret on each string), appropriately named:</p>
<p><img src="http://www.jspatterns.com/wp-content/uploads/2011/08/layers.jpg" alt="" title="layers" width="213" height="346" class="alignnone size-full wp-image-92" /></p>
<p>The task is to get the chord configuration, show the corresponding layers and save the file with the chord name as filename.</p>
<p>So I did this manually (while recording the generated code): show a layer, save the file.</p>
<h3>Show/hide layers</h3>
<p>The generated code for showing a layer looked like an oddly indented piece of overhead:</p>
<pre>
/////// GENERATED - DON'T!

// =======================================================
var idShw = charIDToTypeID( "Shw " );
    var desc2 = new ActionDescriptor();
    var idnull = charIDToTypeID( "null" );
        var list1 = new ActionList();
            var ref1 = new ActionReference();
            var idLyr = charIDToTypeID( "Lyr " );
            ref1.putName( idLyr, "11" );
        list1.putReference( ref1 );
    desc2.putList( idnull, list1 );
executeAction( idShw, desc2, DialogModes.NO );
</pre>
<p>This goes out the door since it can be replaced with:</p>
<pre>app.documents[0].layers.getByName('11').visible = true;</pre>
<p>(11 means first fret on first string)</p>
<h3>Save for web</h2>
<p>The generated code for saving a PNG is even worse, but I simply reindented it and shoved in into a function and that was that.</p>
<pre>
function saveFile(filename) {
    // the following is mostly auto-generated by PS
    var idExpr = charIDToTypeID( "Expr" );
    var desc14 = new ActionDescriptor();

    /// 200 more lines...
}
</pre>
<h3>All the chords</h3>
<p>Finally the part that I actually had to write myself.</p>
<p>Directives:</p>
<pre>
#target photoshop
#include "../../lib/m.js"
</pre>
<p>Notice how easy it is to include a JS file, in my case the data model m.js?</p>
<p>Singe var pattern:</p>
<pre>
var data,
    i, c, v,
    layer,
    layers = app.documents[0].layers;
</pre>
<p>The <code>mojo</code> object comes from m.js. How it works is not very important. The thing is it has a <code>mojo.guitar.getChord()</code> method. You give it a chord name and it returns an array - which fret needs to be pressed on each string. </p>
<pre>
// mojo.guitar.getChord('Am')
// returns [ignore, 0, 1, 2, 2, 0, x]
</pre>
<p>All we need to do then is loop though the array and show the layers. Then save the file (e.g. Am.png) and then hide the same layers so they don't interfere the next chord. So this is the end result which generates all the chords m.js knows about:</p>
<pre>
for (c = 0; c < mojo.prettytones.length; c++) {
    for (v = 0; v < mojo.allchords.length; v++) {
        chord = mojo.prettytones[c].split('/')[0];
        chord += mojo.allchords[v];
        data = mojo.guitar.getChord(chord);
        for (i = 1; i <= 6; i++) {
            layer = "" + i + data[i];
            layers.getByName(layer).visible = true;
        }
        chord = chord.replace('#', '-sharp');
        saveFile('~/stoyan/mojo/chords/images/' + chord + '.png');
        for (i = 1; i <= 6; i++) {
            layer = "" + i + data[i];
            layers.getByName(layer).visible = false;
        }
    }
}
</pre>
<p>Run it and that's it - a bunch of PNG images are written.</p>
<p><img src="http://www.jspatterns.com/wp-content/uploads/2011/08/preview.png" alt="" title="preview" width="650" class="alignnone size-full wp-image-93" /></p>
<h2>Linkies</h2>
<ul>
<li><a href="http://mojotune.com/chords/ui/ps/mojochords.jsx">mojotune.jsx</a> - The final script</li>
<li><a href="http://mojotune.com/chords/lib/m.js">m.js</a> - the data model ("Check out Guitar George, he knows all the chords" - Dire Straits)</li>
<li><a href="http://mojotune.com/chords/images/">images</a> - the generated chord PNGs</li>
<li>JS everywhere: <a href="http://www.slideshare.net/stoyan/javascript-is-everywhere">slides</a> and <a href="http://www.phpied.com/files/jseverywhere.zip">code</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.jspatterns.com/scripting-photoshop-with-javascript/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>JavaScript classes</title>
		<link>http://www.jspatterns.com/javascript-classes/</link>
		<comments>http://www.jspatterns.com/javascript-classes/#comments</comments>
		<pubDate>Thu, 05 May 2011 23:39:13 +0000</pubDate>
		<dc:creator>stoyan</dc:creator>
				<category><![CDATA[Object creation patterns]]></category>
		<category><![CDATA[class]]></category>

		<guid isPermaLink="false">http://www.jspatterns.com/?p=83</guid>
		<description><![CDATA[OK, think of it as a religious flamewar to the likes of "tabs vs. spaces for indentation". Looks like this particular war is currently (at JSConf and NodeConf) even more heated than it should be. Classes vs prototypes. For or against classes. I personally don't care about the "winner". The thing is that classes currently [...]]]></description>
			<content:encoded><![CDATA[<p>OK, think of it as a religious flamewar to the likes of "tabs vs. spaces for indentation". Looks like this particular war is currently (at JSConf and NodeConf) even more heated than it should be. Classes vs prototypes. For or against classes.</p>
<p>I personally don't care about the "winner". The thing is that classes currently don't exist in JavaScript. No such thing. However looks like they might in the next iterations of the language (see <a href="http://brendaneich.com/2011/05/my-jsconf-us-presentation/">latest post from Brendan Eich</a>). Some people miss classes so much that they start calling other things classes or come up with some approximation. Problem is, because classes don't exist, <em>people often mean different things when they say "class"</em>.</p>
<p>Sometimes they mean "constructor functions". Sometimes they mean a regular object literal (singleton-type thing. Heck, "singleton" is also open for interpretations). Sometimes they mean an object or a function defined using Crockford's module pattern. </p>
<p>Sometimes it's some completely different home-grown (or library-provided) thingie called <code>klass</code> for example (in my "JavaScript Patterns" book I have one example for educational/thought-provoking purposes). It has to be <code>klass</code>, or <code>_class</code> or something weird. Because <code>class</code> is a reserved word. Unused, but reserved. And one day may be full of meaning. See the problem?</p>
<p>I avoid saying "class". It just doesn't exist. Imagine two months down the road ECMAScript comes up with classes. And they will most certainly not be the classes you may mean today (e.g. classes won't be another name for constructor functions, I'm sure). </p>
<p>So any written text/blog/documentation you've produced will become incorrect and even worse - misleading and confusing.</p>
<p>To summarize:</p>
<ul>
<li>saying "class" today is confusing and takes extra effort to process (what do you mean? what was that again? it doesn't really exist and is not defined in the language, so an extra <em>translation</em> step is required)</li>
<li>saying "class" today will read plain wrong tomorrow, will confuse and misinform</li>
</ul>
<p>Note:<br />
Heck, even I have this "<a href="http://www.phpied.com/3-ways-to-define-a-javascript-class/">how to define a JavaScript class</a>" post on my other blog. I wrote it years ago when, coming from PHP, I was curious how stuff works in JavaScript. Well I got it wrong then. But fixed it not too long ago because it was top 1 result in google and Yahoo search for "javascript class" and "javascript classes" and I didn't want to continue contributing to the confusion.</p>
<p>Note 2:<br />
To my regret, I couldn't make it to JSConf (aka the best!) nor NodeConf this year (because all girls and women in my life are born in May and it's impossible to travel) so I may be a little off on the level of flamewarfare, but according to Twitter I'm not.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jspatterns.com/javascript-classes/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>And the winner is&#8230;</title>
		<link>http://www.jspatterns.com/and-the-winner-is/</link>
		<comments>http://www.jspatterns.com/and-the-winner-is/#comments</comments>
		<pubDate>Tue, 05 Apr 2011 06:23:01 +0000</pubDate>
		<dc:creator>stoyan</dc:creator>
				<category><![CDATA[books]]></category>

		<guid isPermaLink="false">http://www.jspatterns.com/?p=79</guid>
		<description><![CDATA[In the previous post I announced that one person will win a copy of the Brazilian Portuguese translation of JavaScript Patterns. So here's the winner: @LouMintzer He wins a signed copy of "Padrões JavaScript". Waiting for your mailing address, Lou Update: Lou Doesn't speak Portuguese, so he gets an English copy. The second winner is: [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous post I announced that one person will win a copy of the <a href="http://www.jspatterns.com/javascript-patterns-now-in-brazilian-portuguese/">Brazilian Portuguese translation of JavaScript Patterns</a>. So here's the winner:</p>
<p><a href="http://twitter.com/LouMintzer">@LouMintzer</a></p>
<p>He wins a signed copy of <a href="http://www.novatec.com.br/livros/padroesjavascript/">"Padrões JavaScript"</a>. Waiting for your mailing address, Lou <img src='http://www.jspatterns.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Update: Lou Doesn't speak Portuguese, so he gets an English copy. The second winner is:</p>
<p><a href="http://twitter.com/puresight">@puresight</a></p>
<p>Update: Monty is not too proud of his Portuguese skills either, so third is </p>
<p><a href="http://twitter.com/abozhilov">@abozhilov</a></p>
<p>Asen is an awesome JavaScripter, who actually reviewed the book (thanks a million!) and he already has a copy. Next.</p>
<p><a href="http://twitter.com/mexitek">@mexitek</a></p>
<h2>How I picked the winner</h3>
<p>By writing some JavaScript in the console, of course.</p>
<p>The winner was to be randomly picked from all those who retweet my tweet or post a comment in the announcement. So I had to collect those.</p>
<h3>Twitter</h2>
<p>The <a href="https://twitter.com/stoyanstefanov/status/49323240014872576">tweet page</a> says there has been 27 retweets (worded a bit like 28, but looks like it's 27). The page only shows about 15 people though and I need all of them. Given how Twitter doesn't let you search older stuff, I was afraid it was too late. I had to check the API first. I was expecting I can hit a few URLs and get the data I need. Tough luck. All these auth keys, tokens, secrets and stuff got me floored. </p>
<p>Luckily Twitter's UI is also using the APIs. Checking the network traffic I was able to spot the request I need!</p>
<p><img src="http://www.jspatterns.com/wp-content/uploads/2011/04/win1.jpg" alt="" title="Twitter " width="700" height="495" class="alignnone size-full wp-image-80" /></p>
<p>The URL is:<br />
<code>http://api.twitter.com/1/statuses/49323240014872576/retweeted_by.json?count=15</code><br />
I only needed to change the count to something over 27, so I made it 30. Lo and behold I got the data!</p>
<p>The rest of the stuff I did in Safari's Web Inspector console.</p>
<p>Visiting the URL:<br />
<code>http://api.twitter.com/1/statuses/49323240014872576/retweeted_by.json?count=30</code></p>
<p>We have a JSON array as a document. </p>
<pre>&gt;&gt;&gt; var a = document.body.innerHTML
&gt;&gt;&gt; a
"&lt;pre style="word-wrap: break-word; white-space: pre-wrap;"&gt;[{"profile_link_color":"0084B4","verified":false,"not....]&lt;/pre&gt;"</pre>
<p>Safari puts all in a <code>PRE</code> behind the scenes, so this is how we get the data:</p>
<pre>&gt;&gt;&gt; var source = $$('pre')[0].innerHTML;
&gt;&gt;&gt; source
"[{"profile_link_color":"0084B4","verified":...]"</pre>
<p><code>eval()</code> it:</p>
<pre>&gt;&gt;&gt; source = eval(source)
[Object, Object...]
&gt;&gt;&gt; source.length
27</pre>
<p>Sounds right. Now let's move all usernames into a new array using the new ECMA5 <code>forEach</code> fancy-ness:</p>
<pre>&gt;&gt;&gt; var all = [];
&gt;&gt;&gt; source.forEach(function(e){all.push(e.screen_name)})
&gt;&gt;&gt; all.length
27
&gt;&gt;&gt; all
["jrfaqcom", "gustavobarbosa", "gabrielsilva", ...."vishalkrsingh"]</pre>
<h3>Blog comments</h3>
<p>I had 4 comments on the original post. WordPress puts all comments in a <code>div</code> with class <code>commentlist</code>, so this allows us to grab all comments:</p>
<pre>&gt;&gt;&gt; var comments = $$('.commentlist cite a')
&gt;&gt;&gt; comments.length
4</pre>
<p>Now let's only grab the names, they are in the <code>href</code>'s <code>innerHTML</code>:</p>
<pre>&gt;&gt;&gt; var all = [];
&gt;&gt;&gt; comments[0].innerHTML
"Fabiano Nunes"
&gt;&gt;&gt; comments.forEach(function(e){all.push(e.innerHTML)})
TypeError: Result of expression 'comments.forEach' [undefined] is not a function.</pre>
<p>Eh? What? Oh, the list of <code>HREF</code>s is not an array but a <code>NodeList</code>:</p>
<pre>&gt;&gt;&gt; comments
[
&lt;a href="http://fabiano.nunes.me" rel="external nofollow" class="url"&gt;Fabiano Nunes&lt;/a&gt;
,
&lt;a href="http://www.gabrielizaias.com" rel="external nofollow" class="url"&gt;Gabriel Izaias&lt;/a&gt;
,
&lt;a href="http://www.jrfaq.com.br" rel="external nofollow" class="url"&gt;Jo&atilde;o Rodrigues&lt;/a&gt;
,
&lt;a href="http://www.jrfaq.com.br" rel="external nofollow" class="url"&gt;Jo&atilde;o Rodrigues&lt;/a&gt;
]
&gt;&gt;&gt; comments.forEach
undefined</pre>
<p>So, list of nodes converted to array:</p>
<pre>&gt;&gt;&gt; comments = Array.prototype.slice.call(comments)</pre>
<p>Now <code>forEach</code> is usable:</p>
<pre>&gt;&gt;&gt; comments.forEach
function forEach() {
    [native code]
}
&gt;&gt;&gt; comments.forEach(function(e){all.push(e.innerHTML)})</pre>
<p>So we have a list of all names. Lets serialize it, so it can be pasted to the other window where we had the Twitter data. </p>
<pre>&gt;&gt;&gt; all
["Fabiano Nunes", "Gabriel Izaias", "Jo&atilde;o Rodrigues", "Jo&atilde;o Rodrigues"]
&gt;&gt;&gt; JSON.stringify(all)
"["Fabiano Nunes","Gabriel Izaias","Jo&atilde;o Rodrigues","Jo&atilde;o Rodrigues"]"</pre>
<p>(Simple array join and then string split will do too in this simple example)</p>
<h3>All together</h3>
<p>Back to the twitter window. Deserializing the comments array:</p>
<pre>&gt;&gt;&gt; comments = JSON.parse('["Fabiano Nunes","Gabriel Izaias","Jo&atilde;o Rodrigues","Jo&atilde;o Rodrigues"]')
["Fabiano Nunes", "Gabriel Izaias", "Jo&atilde;o Rodrigues", "Jo&atilde;o Rodrigues"]</pre>
<p>Merging the two arrays</p>
<pre>&gt;&gt;&gt; all = all.concat(comments);
["jrfaqcom", "gustavobarbosa", ...."Jo&atilde;o Rodrigues"]
&gt;&gt;&gt; all.length
31</pre>
<p>Perfect. 31 entries. Just as many as the days in March when I announced it. So let's take the 19th array element to be the winner.</p>
<p>But shuffle the array a bit first.</p>
<h3>Suffle</h3>
<p>Sorting the array by randomness. (I shuffled and reshuffled it three times,  just because.)</p>
<pre>&gt;&gt; all.sort(function() {return 0 - (Math.round(Math.random()))})
["ravidsrk", "anagami", "lpetrov", ...]</pre>
<p>And the winner is:</p>
<pre>&gt;&gt;&gt; all[18]
"LouMintzer"</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.jspatterns.com/and-the-winner-is/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>&#8220;JavaScript Patterns&#8221; now in Brazilian Portuguese</title>
		<link>http://www.jspatterns.com/javascript-patterns-now-in-brazilian-portuguese/</link>
		<comments>http://www.jspatterns.com/javascript-patterns-now-in-brazilian-portuguese/#comments</comments>
		<pubDate>Sun, 20 Mar 2011 04:13:50 +0000</pubDate>
		<dc:creator>stoyan</dc:creator>
				<category><![CDATA[books]]></category>

		<guid isPermaLink="false">http://www.jspatterns.com/?p=76</guid>
		<description><![CDATA[I've been terrible at promoting this book. But that should change starting today So today I got a copy of "Padrões JavaScript" - the Brazilian Portuguese translation of JavaScript Patterns. Happy, happy, happy! Given that I already got two copies few weeks ago, kept one and sent one to my mom for her collection, I [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.phpied.com/images/padroes-javascript.jpg" alt="Padrões JavaScript" /></p>
<p>I've been terrible at promoting this book. But that should change starting today <img src='http://www.jspatterns.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So today I got a copy of <a href="http://www.novatec.com.br/livros/padroesjavascript/">"Padrões JavaScript"</a> - the Brazilian Portuguese translation of <a href="http://www.amazon.com/dp/0596806752">JavaScript Patterns</a>. Happy, happy, happy! </p>
<p>Given that I already got two copies few weeks ago, kept one and sent one to my mom for her collection, I thought I should give this one away.</p>
<p>If you want to enter for a chance to win a signed copy of the Brazilian Portuguese translation of JavaScript Patterns, you can do one or more of the following:</p>
<ul>
<li>Leave a comment below, or/and</li>
<li>Retweet <a href="https://twitter.com/stoyanstefanov/status/49323240014872576">this</a></li>
</ul>
<p>That's it, shipping's on me. Boa sorte!</p>
<p>pssst, here are two PDFs: <a href="http://www.novatec.com.br/livros/padroesjavascript/sumario9788575222669.pdf">table of contents</a> and about <a href="http://www.novatec.com.br/livros/padroesjavascript/capitulo9788575222669.pdf">half of chapter 1</a> for you evaluation pleasure <img src='http://www.jspatterns.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.jspatterns.com/javascript-patterns-now-in-brazilian-portuguese/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Book is almost out</title>
		<link>http://www.jspatterns.com/book-is-almost-out/</link>
		<comments>http://www.jspatterns.com/book-is-almost-out/#comments</comments>
		<pubDate>Sat, 04 Sep 2010 19:25:28 +0000</pubDate>
		<dc:creator>stoyan</dc:creator>
				<category><![CDATA[books]]></category>
		<category><![CDATA[news]]></category>
		<category><![CDATA[book]]></category>

		<guid isPermaLink="false">http://www.jspatterns.com/?p=74</guid>
		<description><![CDATA[The JavaScript Patterns book is to be sent to the printer next week and will be available as expected (and mentioned on Amazon) on or before Sept 28. Yey! Dunno who said: writers don't like to write, they like to have written. Exactly how I feel today. And let me share a quote from my [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.amazon.com/dp/0596806752/?tag=w3clubs-20">JavaScript Patterns</a> book is to be sent to the printer next week and will be available as expected (and mentioned on Amazon) on or before Sept 28. Yey!</p>
<p>Dunno who said: <em>writers don't like to write, they like to have written</em>. Exactly how I feel today. </p>
<p>And let me share a quote from my favorite Kurt Vonnegut along the same lines. The book is <a href="http://www.amazon.com/dp/038533351X/?tag=w3clubs-20">Bluebeard</a>.</p>
<blockquote><p>
&nbsp;&nbsp;&nbsp;&nbsp;She asked me what had been the most pleasing thing about my professional life when I was a full-time painter -- having my first one-man show, getting a lot of money for a picture, the comradeship with fellow painters, being praised by a critic, or what?<br />
&nbsp;&nbsp;&nbsp;&nbsp;"We used to talk a lot about that in the old days," I said. "There was general agreement that if we were put into individual capsules with our art materials, and fired out into different parts of outer space, we would still have everything we loved about painting, which was the opportunity to lay on paint."<br />
&nbsp;&nbsp;&nbsp;&nbsp;I asked her in turn what the high point was for writers -- getting great reviews, or a terrific advance, or selling a book to the movies, or seeing somebody reading your book, or what? She said that she, too, could find happiness in a capsule in outer space, provided that she had a finished, proofread manuscript by her in there, along with somebody from her publishing house.<br />
&nbsp;&nbsp;&nbsp;&nbsp;"I don't understand," I said.<br />
&nbsp;&nbsp;&nbsp;&nbsp;"The orgastic moment for me is when I hand a manuscript to my publisher and say, 'Here! I'm all through with it. I never want to see it again,' " she said.
</p></blockquote>
<p>So - whew!</p>
<p>Expect a more detailed post about the book (and the wonderful team of JS guru tech reviewers!), after all I have to start promoting it, don't I? </p>
]]></content:encoded>
			<wfw:commentRss>http://www.jspatterns.com/book-is-almost-out/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Singleton without a closure</title>
		<link>http://www.jspatterns.com/singleton-without-a-closure/</link>
		<comments>http://www.jspatterns.com/singleton-without-a-closure/#comments</comments>
		<pubDate>Sat, 17 Jul 2010 23:09:26 +0000</pubDate>
		<dc:creator>stoyan</dc:creator>
				<category><![CDATA[Object creation patterns]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://www.jspatterns.com/?p=70</guid>
		<description><![CDATA[Warning: anti-pattern ahead. Mwahaha, I feel like a ninja. I mean a ninja by Doug Crockford's definition which means someone who finds a mistake in the language's design, decides it's cool and abuses it. So there you go. Regular expression objects are created only once if you're using a literal. Such an object can be [...]]]></description>
			<content:encoded><![CDATA[<p>Warning: anti-pattern ahead.</p>
<p>Mwahaha, I feel like a ninja. I mean a ninja by Doug Crockford's definition which means someone who finds a mistake in the language's design, decides it's cool and abuses it.</p>
<p>So there you go. Regular expression objects are created only once if you're using a literal. Such an object can be used to store the single instance of a Singleton() constructor.</p>
<h4>Implementation</h4>
<div class="hl-main">
<pre><span class="hl-reserved">function</span><span class="hl-code"> </span><span class="hl-identifier">Single</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
    </span><span class="hl-quotes">&quot;</span><span class="hl-string">strict me not!</span><span class="hl-quotes">&quot;</span><span class="hl-code">;

    </span><span class="hl-reserved">var</span><span class="hl-code"> </span><span class="hl-identifier">re</span><span class="hl-code"> = / /;
    </span><span class="hl-reserved">if</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">re</span><span class="hl-code">.</span><span class="hl-identifier">instance</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
        </span><span class="hl-reserved">return</span><span class="hl-code"> </span><span class="hl-identifier">re</span><span class="hl-code">.</span><span class="hl-identifier">instance</span><span class="hl-code">;
    </span><span class="hl-brackets">}</span><span class="hl-code">
    </span><span class="hl-identifier">re</span><span class="hl-code">.</span><span class="hl-identifier">instance</span><span class="hl-code"> = </span><span class="hl-reserved">this</span><span class="hl-code">;
    </span><span class="hl-reserved">this</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code"> = </span><span class="hl-quotes">&quot;</span><span class="hl-string">Foo</span><span class="hl-quotes">&quot;</span><span class="hl-code">;

</span><span class="hl-brackets">}</span><span class="hl-code">

</span><span class="hl-identifier">Single</span><span class="hl-code">.</span><span class="hl-identifier">prototype</span><span class="hl-code">.</span><span class="hl-identifier">getName</span><span class="hl-code"> = </span><span class="hl-reserved">function</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
    </span><span class="hl-reserved">return</span><span class="hl-code"> </span><span class="hl-reserved">this</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code">;
</span><span class="hl-brackets">}</span><span class="hl-code">;</span></pre>
</div>
<h4>Test</h4>
<div class="hl-main">
<pre><span class="hl-reserved">var</span><span class="hl-code"> </span><span class="hl-identifier">s1</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">Single</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">,
    </span><span class="hl-identifier">s2</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">Single</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;

</span><span class="hl-identifier">console</span><span class="hl-code">.</span><span class="hl-identifier">log</span><span class="hl-brackets">(</span><span class="hl-identifier">s1</span><span class="hl-code"> === </span><span class="hl-identifier">s2</span><span class="hl-brackets">)</span><span class="hl-code">; </span><span class="hl-comment">//</span><span class="hl-comment"> true</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-identifier">console</span><span class="hl-code">.</span><span class="hl-identifier">log</span><span class="hl-brackets">(</span><span class="hl-identifier">s1</span><span class="hl-code">.</span><span class="hl-identifier">getName</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-brackets">)</span><span class="hl-code">; </span><span class="hl-comment">//</span><span class="hl-comment"> &quot;Foo&quot;</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-identifier">s1</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code"> = </span><span class="hl-quotes">&quot;</span><span class="hl-string">dude</span><span class="hl-quotes">&quot;</span><span class="hl-code">;
</span><span class="hl-identifier">console</span><span class="hl-code">.</span><span class="hl-identifier">log</span><span class="hl-brackets">(</span><span class="hl-identifier">s2</span><span class="hl-code">.</span><span class="hl-identifier">getName</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-brackets">)</span><span class="hl-code">; </span><span class="hl-comment">//</span><span class="hl-comment"> &quot;dude&quot;</span><span class="hl-comment"></span></pre>
</div>
<h4>Pros</h4>
<ul>
<li>The prototype chain works fine</li>
<li>No closures</li>
<li>No public properties or globals to store the single instance</li>
</ul>
<h4>Cons</h4>
<ul>
<li>It's a hack</li>
<li>ES5 defines that reg exp literals should no longer work like this</li>
</ul>
<h4>Verdict</h4>
<p>Don't use. Please <img src='http://www.jspatterns.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.jspatterns.com/singleton-without-a-closure/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Constants</title>
		<link>http://www.jspatterns.com/constants/</link>
		<comments>http://www.jspatterns.com/constants/#comments</comments>
		<pubDate>Sat, 10 Apr 2010 07:12:26 +0000</pubDate>
		<dc:creator>stoyan</dc:creator>
				<category><![CDATA[Functions]]></category>
		<category><![CDATA[closure]]></category>
		<category><![CDATA[constants]]></category>
		<category><![CDATA[private]]></category>

		<guid isPermaLink="false">http://www.jspatterns.com/?p=69</guid>
		<description><![CDATA[Although there actually are constants in some environments, e.g. in Firefox you can use const instead of var, in general in JavaScript there are no constants. Workaround To work around that limitation, people often use ALLCAPPS to denote "hey, don't touch this var, it's meant to be a constant". It's constant-by-convention but the values can [...]]]></description>
			<content:encoded><![CDATA[<p>Although there actually are constants in some environments, e.g. in Firefox you can use <code>const</code> instead of <code>var</code>, in general in JavaScript there are no constants.</p>
<h2>Workaround</h2>
<p>To work around that limitation, people often use ALLCAPPS to denote "hey, don't touch this var, it's meant to be a constant". It's constant-by-convention but the values can be changed by careless programmer on a bad day. If you really want to protect the value, you need to make it private.</p>
<h2>PHP-inspired API</h2>
<p>In PHP there are the functions <code>define(<em>name</em>, <em>value</em>)</code> to gefine a constant, <code>defined(<em>name</em>)</code> to check if a constant is defined and <code>constant(<em>name</em>)</code> to get the value of a constants when it's name is assembled at runtime and you don't know it <em>a priori</em>. So I thought - well, we can do the same in JavaScript. Only, let's not use global functions, but a <code>constant</code> global var and make the functions method of that global. <code>constant.constant(<em>name</em>)</code> is a little mouthful, so let's make that one <code>constant.get(<em>name</em>)</code></p>
<h2>Implementation</h2>
<p>Here's the simple implementation:</p>
<div class="hl-main">
<pre><span class="hl-quotes">&quot;</span><span class="hl-string">use strict</span><span class="hl-quotes">&quot;</span><span class="hl-code">;

</span><span class="hl-reserved">var</span><span class="hl-code"> </span><span class="hl-identifier">constant</span><span class="hl-code"> = </span><span class="hl-brackets">(</span><span class="hl-reserved">function</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
    </span><span class="hl-reserved">var</span><span class="hl-code"> </span><span class="hl-identifier">constants</span><span class="hl-code"> = </span><span class="hl-brackets">{</span><span class="hl-brackets">}</span><span class="hl-code">,
        </span><span class="hl-identifier">ownProp</span><span class="hl-code"> = </span><span class="hl-identifier">Object</span><span class="hl-code">.</span><span class="hl-identifier">prototype</span><span class="hl-code">.</span><span class="hl-identifier">hasOwnProperty</span><span class="hl-code">,
        </span><span class="hl-identifier">allowed</span><span class="hl-code"> = </span><span class="hl-brackets">{</span><span class="hl-code">
            </span><span class="hl-identifier">string</span><span class="hl-code">: </span><span class="hl-number">1</span><span class="hl-code">,
            </span><span class="hl-identifier">number</span><span class="hl-code">: </span><span class="hl-number">1</span><span class="hl-code">,
            </span><span class="hl-reserved">boolean</span><span class="hl-code">: </span><span class="hl-number">1</span><span class="hl-code">
        </span><span class="hl-brackets">}</span><span class="hl-code">;
    </span><span class="hl-reserved">return</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
        </span><span class="hl-identifier">define</span><span class="hl-code">: </span><span class="hl-reserved">function</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">name</span><span class="hl-code">, </span><span class="hl-identifier">value</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
            </span><span class="hl-reserved">if</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-reserved">this</span><span class="hl-code">.</span><span class="hl-identifier">defined</span><span class="hl-brackets">(</span><span class="hl-identifier">name</span><span class="hl-brackets">)</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
                </span><span class="hl-reserved">return</span><span class="hl-code"> </span><span class="hl-reserved">false</span><span class="hl-code">;
            </span><span class="hl-brackets">}</span><span class="hl-code">
            </span><span class="hl-reserved">if</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-code">!</span><span class="hl-identifier">ownProp</span><span class="hl-code">.</span><span class="hl-identifier">call</span><span class="hl-brackets">(</span><span class="hl-identifier">allowed</span><span class="hl-code">, </span><span class="hl-reserved">typeof</span><span class="hl-code"> </span><span class="hl-identifier">value</span><span class="hl-brackets">)</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
                </span><span class="hl-reserved">return</span><span class="hl-code"> </span><span class="hl-reserved">false</span><span class="hl-code">;
            </span><span class="hl-brackets">}</span><span class="hl-code">
            </span><span class="hl-identifier">constants</span><span class="hl-brackets">[</span><span class="hl-identifier">name</span><span class="hl-brackets">]</span><span class="hl-code"> = </span><span class="hl-identifier">value</span><span class="hl-code">;
            </span><span class="hl-reserved">return</span><span class="hl-code"> </span><span class="hl-reserved">true</span><span class="hl-code">;
        </span><span class="hl-brackets">}</span><span class="hl-code">,
        </span><span class="hl-identifier">defined</span><span class="hl-code">: </span><span class="hl-reserved">function</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">name</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
            </span><span class="hl-reserved">return</span><span class="hl-code"> </span><span class="hl-identifier">ownProp</span><span class="hl-code">.</span><span class="hl-identifier">call</span><span class="hl-brackets">(</span><span class="hl-identifier">constants</span><span class="hl-code">, </span><span class="hl-identifier">name</span><span class="hl-brackets">)</span><span class="hl-code">;
        </span><span class="hl-brackets">}</span><span class="hl-code">,
        </span><span class="hl-identifier">get</span><span class="hl-code">: </span><span class="hl-reserved">function</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-identifier">name</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
            </span><span class="hl-reserved">if</span><span class="hl-code"> </span><span class="hl-brackets">(</span><span class="hl-reserved">this</span><span class="hl-code">.</span><span class="hl-identifier">defined</span><span class="hl-brackets">(</span><span class="hl-identifier">name</span><span class="hl-brackets">)</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
                </span><span class="hl-reserved">return</span><span class="hl-code"> </span><span class="hl-identifier">constants</span><span class="hl-brackets">[</span><span class="hl-identifier">name</span><span class="hl-brackets">]</span><span class="hl-code">;
            </span><span class="hl-brackets">}</span><span class="hl-code">
            </span><span class="hl-reserved">return</span><span class="hl-code"> </span><span class="hl-reserved">null</span><span class="hl-code">;
        </span><span class="hl-brackets">}</span><span class="hl-code">
    </span><span class="hl-brackets">}</span><span class="hl-code">;
</span><span class="hl-brackets">}</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-brackets">)</span><span class="hl-code">;</span></pre>
</div>
<p>This is it. Basically protect an object in a closure and don't provide means to change it, but only to add properties to it.</p>
<p>UPDATE: thanks to the comments (see below), there's extra care to check for own properties of the <code>constants</code> private object. This allows to define constants with weird names such as <code>toString</code> and <code>hasOwnProperty</code>. Also only primitive values are allowed to be constants.</p>
<h2>Usage</h2>
<div class="hl-main">
<pre><span class="hl-comment">//</span><span class="hl-comment"> check if defined</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-identifier">constant</span><span class="hl-code">.</span><span class="hl-identifier">defined</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">bazinga</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">; </span><span class="hl-comment">//</span><span class="hl-comment"> false</span><span class="hl-comment"></span><span class="hl-code">

</span><span class="hl-comment">//</span><span class="hl-comment"> define</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-identifier">constant</span><span class="hl-code">.</span><span class="hl-identifier">define</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">bazinga</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-quotes">&quot;</span><span class="hl-string">Bazinga!</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">; </span><span class="hl-comment">//</span><span class="hl-comment"> true</span><span class="hl-comment"></span><span class="hl-code">

</span><span class="hl-comment">//</span><span class="hl-comment"> check again</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-identifier">constant</span><span class="hl-code">.</span><span class="hl-identifier">defined</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">bazinga</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">; </span><span class="hl-comment">//</span><span class="hl-comment"> true</span><span class="hl-comment"></span><span class="hl-code">

</span><span class="hl-comment">//</span><span class="hl-comment"> attempt to redefine</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-identifier">constant</span><span class="hl-code">.</span><span class="hl-identifier">define</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">bazinga</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-quotes">&quot;</span><span class="hl-string">Bazinga2</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">; </span><span class="hl-comment">//</span><span class="hl-comment"> false</span><span class="hl-comment"></span><span class="hl-code">

</span><span class="hl-comment">//</span><span class="hl-comment"> was it constant or it changed?</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-comment">//</span><span class="hl-comment"> get da, get da, get da value</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-identifier">constant</span><span class="hl-code">.</span><span class="hl-identifier">get</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">bazinga</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">; </span><span class="hl-comment">//</span><span class="hl-comment"> &quot;Bazinga!&quot;</span><span class="hl-comment"></span></pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.jspatterns.com/constants/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>arguments considered harmful</title>
		<link>http://www.jspatterns.com/arguments-considered-harmful/</link>
		<comments>http://www.jspatterns.com/arguments-considered-harmful/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 08:04:42 +0000</pubDate>
		<dc:creator>stoyan</dc:creator>
				<category><![CDATA[Coding practices]]></category>
		<category><![CDATA[arguments]]></category>
		<category><![CDATA[callee]]></category>
		<category><![CDATA[POLA]]></category>

		<guid isPermaLink="false">http://www.jspatterns.com/?p=68</guid>
		<description><![CDATA[Inside every JavaScript function an arguments object is available containing all the parameters passed to the function. function aha(a, b) { console.log(arguments[0] === a); // true console.log(arguments[1] === b); // true } aha(1, 2); However, it's not a good idea to use arguments for the reasons of : performance security The arguments object is not [...]]]></description>
			<content:encoded><![CDATA[<p>Inside every JavaScript function an <code>arguments</code> object is available containing all the parameters passed to the function. </p>
<div class="hl-main">
<pre><span class="hl-reserved">function</span><span class="hl-code"> </span><span class="hl-identifier">aha</span><span class="hl-brackets">(</span><span class="hl-identifier">a</span><span class="hl-code">, </span><span class="hl-identifier">b</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
  </span><span class="hl-identifier">console</span><span class="hl-code">.</span><span class="hl-identifier">log</span><span class="hl-brackets">(</span><span class="hl-identifier">arguments</span><span class="hl-brackets">[</span><span class="hl-number">0</span><span class="hl-brackets">]</span><span class="hl-code"> === </span><span class="hl-identifier">a</span><span class="hl-brackets">)</span><span class="hl-code">; </span><span class="hl-comment">//</span><span class="hl-comment"> true</span><span class="hl-comment"></span><span class="hl-code">
  </span><span class="hl-identifier">console</span><span class="hl-code">.</span><span class="hl-identifier">log</span><span class="hl-brackets">(</span><span class="hl-identifier">arguments</span><span class="hl-brackets">[</span><span class="hl-number">1</span><span class="hl-brackets">]</span><span class="hl-code"> === </span><span class="hl-identifier">b</span><span class="hl-brackets">)</span><span class="hl-code">; </span><span class="hl-comment">//</span><span class="hl-comment"> true</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-brackets">}</span><span class="hl-code">

</span><span class="hl-identifier">aha</span><span class="hl-brackets">(</span><span class="hl-number">1</span><span class="hl-code">, </span><span class="hl-number">2</span><span class="hl-brackets">)</span><span class="hl-code">;</span></pre>
</div>
<p>However, it's not a good idea to use <code>arguments</code> for the reasons of :</p>
<ul>
<li>performance</li>
<li>security</li>
</ul>
<p>The <code>arguments</code> object is not automatically created every time the function is called, the JavaScript engine will only create it on-demand, if it's used. And that creation is not free in terms of performance. The difference between using arguments vs. not using it could be anywhere between <strong>1.5 times to 4 times slower</strong>, depending on the browser (<a href="http://webreflection.blogspot.com/2010/02/arguments-callee-call-and-apply.html">more info and bench</a>)</p>
<p>As for the security, there is the <a href="http://en.wikipedia.org/wiki/Principle_of_least_authority">POLA</a> (Principle of Least Authority) which is violated when one function A passes <code>arguments</code> to another B. Then a number of bad things can happen including:</p>
<ul>
<li>B calls A through arguments.callee - something A never intended when calling B in the first place</li>
<li>B overwrites some <code>arguments</code> and causes A to misbehave</li>
</ul>
<p>While in these scenarios B looks a little malicious, it can actually cause trouble unvoluntarilly. Consider this example that illustrates the second case (B changing values behind A's unsuspecting back)</p>
<div class="hl-main">
<pre><span class="hl-reserved">function</span><span class="hl-code"> </span><span class="hl-identifier">A</span><span class="hl-brackets">(</span><span class="hl-identifier">obj</span><span class="hl-code">, </span><span class="hl-identifier">ar</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">

  </span><span class="hl-identifier">console</span><span class="hl-code">.</span><span class="hl-identifier">log</span><span class="hl-brackets">(</span><span class="hl-identifier">obj</span><span class="hl-brackets">)</span><span class="hl-code">; </span><span class="hl-comment">//</span><span class="hl-comment"> {p: 1}</span><span class="hl-comment"></span><span class="hl-code">
  </span><span class="hl-identifier">console</span><span class="hl-code">.</span><span class="hl-identifier">log</span><span class="hl-brackets">(</span><span class="hl-identifier">ar</span><span class="hl-brackets">)</span><span class="hl-code">;  </span><span class="hl-comment">//</span><span class="hl-comment"> [1, 2, 3]</span><span class="hl-comment"></span><span class="hl-code">

  </span><span class="hl-identifier">B</span><span class="hl-brackets">(</span><span class="hl-identifier">arguments</span><span class="hl-brackets">)</span><span class="hl-code">;

  </span><span class="hl-comment">//</span><span class="hl-comment"> oops!</span><span class="hl-comment"></span><span class="hl-code">
  </span><span class="hl-identifier">console</span><span class="hl-code">.</span><span class="hl-identifier">log</span><span class="hl-brackets">(</span><span class="hl-identifier">obj</span><span class="hl-brackets">)</span><span class="hl-code">; </span><span class="hl-comment">//</span><span class="hl-comment"> {p: 2}</span><span class="hl-comment"></span><span class="hl-code">
  </span><span class="hl-identifier">console</span><span class="hl-code">.</span><span class="hl-identifier">log</span><span class="hl-brackets">(</span><span class="hl-identifier">ar</span><span class="hl-brackets">)</span><span class="hl-code">;  </span><span class="hl-comment">//</span><span class="hl-comment"> [1, 2]</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-brackets">}</span><span class="hl-code">

</span><span class="hl-reserved">function</span><span class="hl-code"> </span><span class="hl-identifier">B</span><span class="hl-brackets">(</span><span class="hl-identifier">args</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">

  </span><span class="hl-comment">//</span><span class="hl-comment"> convenient innocent-looking local vars</span><span class="hl-comment"></span><span class="hl-code">
  </span><span class="hl-reserved">var</span><span class="hl-code"> </span><span class="hl-identifier">o</span><span class="hl-code">=</span><span class="hl-identifier">args</span><span class="hl-brackets">[</span><span class="hl-number">0</span><span class="hl-brackets">]</span><span class="hl-code">,
      </span><span class="hl-identifier">a</span><span class="hl-code">=</span><span class="hl-identifier">args</span><span class="hl-brackets">[</span><span class="hl-number">1</span><span class="hl-brackets">]</span><span class="hl-code">;

  </span><span class="hl-comment">//</span><span class="hl-comment"> do something with the local variables</span><span class="hl-comment"></span><span class="hl-code">
  </span><span class="hl-identifier">o</span><span class="hl-code">.</span><span class="hl-identifier">p</span><span class="hl-code"> = </span><span class="hl-number">2</span><span class="hl-code">;
  </span><span class="hl-identifier">a</span><span class="hl-code">.</span><span class="hl-identifier">pop</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;

  </span><span class="hl-comment">//</span><span class="hl-comment"> now the original arguments is </span><span class="hl-comment"></span><span class="hl-code">
  </span><span class="hl-comment">//</span><span class="hl-comment"> messed up because objects/arrays</span><span class="hl-comment"></span><span class="hl-code">
  </span><span class="hl-comment">//</span><span class="hl-comment"> are passed by reference</span><span class="hl-comment"></span><span class="hl-code">
</span><span class="hl-brackets">}</span><span class="hl-code">

</span><span class="hl-identifier">A</span><span class="hl-brackets">(</span><span class="hl-brackets">{</span><span class="hl-identifier">p</span><span class="hl-code">: </span><span class="hl-number">1</span><span class="hl-brackets">}</span><span class="hl-code">, </span><span class="hl-brackets">[</span><span class="hl-number">1</span><span class="hl-code">, </span><span class="hl-number">2</span><span class="hl-code">, </span><span class="hl-number">3</span><span class="hl-brackets">]</span><span class="hl-brackets">)</span><span class="hl-code">;</span></pre>
</div>
<h2>ECMAScript 5</h2>
<p>In ECMAScript's "strict mode", using <code>arguments.callee</code> will throw a syntax error.</p>
<h2>Recursive anonymous function</h2>
<p>Probably the biggest argument for keeping <code>arguments</code> and <code>arguments.callee</code> is so that recursive anonymous functions can be created, because by using the <code>callee</code> property a function can call itself without knowing its own name. Now, this is not such a common scenario, but even if so, you can wrap a named function inside of an anonymous function and voila! - call that named function recursively without leaking a variable to the global scope.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jspatterns.com/arguments-considered-harmful/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

