<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-542398624287876588</atom:id><lastBuildDate>Tue, 09 Feb 2010 13:27:45 +0000</lastBuildDate><title>Nifty Snippets</title><description>Nifty Snippets&lt;sup&gt;TM&lt;/sup&gt; of code, techniques, and information focussing on Ajax, web scripting, and engineering.</description><link>http://blog.niftysnippets.org/</link><managingEditor>noreply@blogger.com (T.J. Crowder)</managingEditor><generator>Blogger</generator><openSearch:totalResults>21</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/NiftySnippets" /><feedburner:info uri="niftysnippets" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-2307042243273092963</guid><pubDate>Tue, 09 Feb 2010 13:03:00 +0000</pubDate><atom:updated>2010-02-09T13:27:45.407Z</atom:updated><title>catch...from</title><description>A brief post off my usual JavaScript track for a digression into Java and related languages (although come to think of it, the concept below applies just as much to JavaScript as Java).&lt;br /&gt;&lt;br /&gt;Exception handling features in languages are fantastic. They let us (if we're careful and thorough) express the mainline logic of our code uninterrupted by the niggly little detail that just about anything can fail at just about any time, and then let us handle those failures in clearly-defined "...and if that goes wrong, do this" blocks. In pseudocode:&lt;br /&gt;&lt;pre&gt;try&lt;br /&gt;{&lt;br /&gt;    doThis();&lt;br /&gt;    doThat();&lt;br /&gt;    doTheOther();&lt;br /&gt;    return result;&lt;br /&gt;}&lt;br /&gt;catch (ExceptionalCondition ec)&lt;br /&gt;{&lt;br /&gt;    // Handle it&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Lovely and wonderful. We were able to express what we're really trying to do (this, that, and the other) clearly, but then handle the fact that this, that, or the other can fail. The equivalent in, say, C would be to use the convention that returning 0 means everything was fine and returning !0 means something went wrong:&lt;br /&gt;&lt;pre&gt;if (doThis() == 0)&lt;br /&gt;{&lt;br /&gt;    if (doThat() == 0)&lt;br /&gt;    {&lt;br /&gt;        if (doTheOther() == 0)&lt;br /&gt;        {&lt;br /&gt;            return result;&lt;br /&gt;        }&lt;br /&gt;     }&lt;br /&gt;}&lt;br /&gt;// Handle the fact that something failed&lt;/pre&gt;(Although you probably wouldn't write it &lt;em&gt;quite&lt;/em&gt; like that.)&lt;br /&gt;&lt;br /&gt;So for obvious reasons I'm a big fan of exception constructs, but there's a refinement I've been wanting for a good 10+ years now (maybe it's about time I got around to submitting a JSR or something; they don't seem to be getting my telepathic messages):&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;&lt;code&gt;catch..from&lt;/code&gt;&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;This is probably best expressed with an example:&lt;br /&gt;&lt;pre&gt;FileOutputStream    output;&lt;br /&gt;Socket              socket;&lt;br /&gt;InputStream         input;&lt;br /&gt;byte[]              buffer;&lt;br /&gt;int                 count;&lt;br /&gt;&lt;br /&gt;// Not shown: Opening the input and output, allocating the buffer,&lt;br /&gt;// getting the socket's input stream&lt;br /&gt;&lt;br /&gt;try&lt;br /&gt;{&lt;br /&gt;    while (/* ... */)&lt;br /&gt;    {&lt;br /&gt;        count = input.read(buffer, 0, buffer.length);&lt;br /&gt;        output.write(buffer, 0, count);&lt;br /&gt;&lt;br /&gt;        // ...&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;catch (IOException ioe from input)&lt;br /&gt;{&lt;br /&gt;    // Handle the error reading the socket&lt;br /&gt;}&lt;br /&gt;catch (IOException ioe from output)&lt;br /&gt;{&lt;br /&gt;    // Handle the error writing to the file&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;As you can see, the goal here is to separate the logic that handles errors reading from the socket from the completely unrelated logic that handles errors writing to the file.&lt;br /&gt;&lt;br /&gt;A very basic idea, but I've never heard of anyone implementing it. This may be because I'm so shockingly brilliant that no one else has ever thought of this. (A kind reader will not immediately consider the converse argument.) Or, more likely, there are a lot of subtleties involved that make it tricky.&lt;br /&gt;&lt;br /&gt;For instance, exceptions thrown by other objects being used under-the-covers by the socket or file output stream instance need to be handled as though thrown by the socket or output stream instance once they get to the level where we've caught them. But that shouldn't be that hard, although it would require that the stack trace record instance information.&lt;br /&gt;&lt;br /&gt;Another wrinkle comes from checked exceptions: Does my code above throw IOException, or not? I've caught it if it's thrown by &lt;code&gt;input&lt;/code&gt; or &lt;code&gt;output&lt;/code&gt;, and those are the only two instances I've used methods on that may throw the exception, so no, my code doesn't throw &lt;code&gt;IOException&lt;/code&gt;. But it'll require enhancing compilers so they can figure that out. But that, too, doesn't seem that complicated.&lt;br /&gt;&lt;br /&gt;It's very hard to do the above (in a general way) without language support, hence the suggestion that it may be worth adding a construct to the language.&lt;br /&gt;&lt;br /&gt;Happy coding.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-2307042243273092963?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/tpzTKoHDtm4" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/tpzTKoHDtm4/catchfrom.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2010/02/catchfrom.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-6699035637403119654</guid><pubDate>Thu, 17 Dec 2009 13:53:00 +0000</pubDate><atom:updated>2009-12-17T13:59:03.654Z</atom:updated><title>GET information, POST changes</title><description>A micro-post, but this isn't said often enough: Don't use &lt;code&gt;GET&lt;/code&gt; requests to change data server-side, use &lt;code&gt;POST&lt;/code&gt; (for example, when using Ajax to modify things server-side). &lt;code&gt;GET&lt;/code&gt;s are supposed to be &lt;a href="http://dictionary.reference.com/browse/idempotent"&gt;idempotent&lt;/a&gt;, which is a fancy way of saying that doing them repeatedly has the same effect as doing them once. So, &lt;code&gt;GET&lt;/code&gt; the contents of a message on a message board, but &lt;code&gt;POST&lt;/code&gt; new messages to the board.&lt;br /&gt;&lt;br /&gt;More (in incredibly turgid prose!) in &lt;a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.2"&gt;Section 9.1.2 of the HTTP spec&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-6699035637403119654?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/oUyJwC-08Vw" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/oUyJwC-08Vw/get-information-post-changes.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2009/12/get-information-post-changes.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-6089847706376114893</guid><pubDate>Tue, 13 Oct 2009 11:59:00 +0000</pubDate><atom:updated>2009-10-13T13:41:04.876+01:00</atom:updated><title>A better way to hide .htaccess, WEB-INF</title><description>If you use Apache as your web server of choice, you may wish to have files or directories that Apache pretends are not there. For me, this is because I like to have Apache proxy a servlet container backend, but I'm too lazy to separate out the files, and so I just point Apache and the servlet container at the same directory and tell Apache to pass on the relevant requests to the servlet container (e.g. JSPs, servlets, etc.). The only problem is, that common directory will tend to contain things like the &lt;code&gt;WEB-INF&lt;/code&gt; directory and its subdirectories, which I &lt;em&gt;kind of&lt;/em&gt; don't want Apache to serve up to the public!  If you use &lt;code&gt;.htaccess&lt;/code&gt; files, you'll have the same sort of situation.&lt;br /&gt;&lt;br /&gt;The usual answer is to simply deny access to the file or directory in question, as in this default rule from the Apache2 config:&lt;br /&gt;&lt;pre&gt;&amp;lt;Files ~ "^\.ht"&amp;gt;&lt;br /&gt;    Order allow,deny&lt;br /&gt;    Deny from all&lt;br /&gt;&amp;lt;/Files&amp;gt;&lt;/pre&gt;That sends a 403 (Forbidden) reply when someone tries to access &lt;code&gt;.htaccess&lt;/code&gt;. And the same sort of thing can be applied for &lt;code&gt;WEB-INF&lt;/code&gt; using the &lt;code&gt;DirectoryMatch&lt;/code&gt; directive:&lt;br /&gt;&lt;pre&gt;&amp;lt;DirectoryMatch "(^|/)WEB-INF($|/)"&amp;gt;&lt;br /&gt;    Deny from all&lt;br /&gt;&amp;lt;/DirectoryMatch&amp;gt;&lt;/pre&gt;And that's great, but I'm a bit paranoid -- why does the outside world need to know that the thing is there &lt;em&gt;at all&lt;/em&gt;? I'd much rather it sent a 404. And huzzah, &lt;code&gt;&lt;a href="http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html"&gt;mod_rewrite&lt;/a&gt;&lt;/code&gt; to the rescue!&lt;br /&gt;&lt;pre&gt;&amp;lt;DirectoryMatch "(^|/)WEB-INF($|/)"&amp;gt;&lt;br /&gt;    RewriteEngine on&lt;br /&gt;    RewriteRule .* - [L,R=404]&lt;br /&gt;&amp;lt;/DirectoryMatch&amp;gt;&lt;/pre&gt;Since the &lt;code&gt;RewriteRule&lt;/code&gt; is already inside the &lt;code&gt;DirectoryMatch&lt;/code&gt; that will only match what we want, its own regex can just match everything. The &lt;code&gt;L&lt;/code&gt; flag says this is the last rule, but the &lt;code&gt;&lt;a href="http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#redirect"&gt;R&lt;/a&gt;&lt;/code&gt; flag is the magic: It forces a redirect, and if you use the &lt;code&gt;R=xyz&lt;/code&gt; form, it redirects with the given code; in this case, a 404. This does the right thing even if you have a custom error document (and you have custom error documents, right?).&lt;br /&gt;&lt;br /&gt;Voil&amp;agrave;! As far as the outside world is concerned, there just isn't a &lt;code&gt;WEB-INF&lt;/code&gt; directory there at all.&lt;br /&gt;&lt;br /&gt;If you like, you can have a general rule that works whether &lt;code&gt;mod_rewrite&lt;/code&gt; is loaded or not:&lt;br /&gt;&lt;pre&gt;&amp;lt;DirectoryMatch "(^|/)WEB-INF($|/)"&amp;gt;&lt;br /&gt;    &amp;lt;IfModule mod_rewrite.c&amp;gt;&lt;br /&gt;        RewriteEngine on&lt;br /&gt;        RewriteRule .* - [L,R=404]&lt;br /&gt;    &amp;lt;/IfModule&amp;gt;&lt;br /&gt;    &amp;lt;IfModule !mod_rewrite.c&amp;gt;&lt;br /&gt;        Deny from all&lt;br /&gt;    &amp;lt;/IfModule&amp;gt;&lt;br /&gt;&amp;lt;/DirectoryMatch&amp;gt;&lt;/pre&gt;This will do a 404 if &lt;code&gt;mod_rewrite&lt;/code&gt; is loaded, but fall back to a 403 of not.&lt;br /&gt;&lt;br /&gt;Final note: If you're letting Apache generate directory listings for you by not including a directory file, the above won't hide the &lt;code&gt;WEB-INF&lt;/code&gt; diretory (or whatever you're hiding) in those listings.  It's easy enough to do it, though:  Inside the relevant directive for the directory being listed, just use &lt;code&gt;&lt;a href="http://httpd.apache.org/docs/2.0/mod/mod_autoindex.html#indexignore"&gt;IndexIgnore&lt;/a&gt;&lt;/code&gt; to tell the &lt;code&gt;mod_autoindex&lt;/code&gt; module to ignore it:&lt;br /&gt;&lt;pre&gt;IndexIgnore WEB-INF&lt;/pre&gt;In my case, since I want &lt;code&gt;WEB-INF&lt;/code&gt; to be hidden everywhere, I can just include it inside my main &lt;code&gt;Directory&lt;/code&gt; directive.  I never let Apache generate listings for me anyway, but it's nice to have a backstop if I blow away my index file.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-6089847706376114893?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/UgyDnSF4XzQ" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/UgyDnSF4XzQ/better-way-to-hide-htaccess-web-inf.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2009/10/better-way-to-hide-htaccess-web-inf.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-4004866189761444001</guid><pubDate>Sun, 13 Sep 2009 14:21:00 +0000</pubDate><atom:updated>2009-09-13T16:09:24.375+01:00</atom:updated><title>Private Methods in JavaScript</title><description>The question of truly private methods comes up intermittently in JavaScript mailing lists. Most respondents point to &lt;a href='http://javascript.crockford.com/private.html'&gt;Crockford's solution&lt;/a&gt;, but then also point out how much memory it takes (each instance gets &lt;em&gt;its own copy&lt;/em&gt; of methods; but on the up side, it also gives you truly private member variables as well as methods).&lt;br /&gt;&lt;br /&gt;Recently I've been switching to the module pattern for each class, thanks in part to kicking around the &lt;a href='http://prototypejs.org'&gt;Prototype&lt;/a&gt; source code a fair bit (and also having read Juriy Zaytsev's &lt;a href='http://yura.thinkweb2.com/named-function-expressions/'&gt;article&lt;/a&gt; on named function expressions). Since private scope is an intrinsic part of the module pattern, I wondered whether it could help us define truly private methods. And the answer is: Of course it can.&lt;br /&gt;&lt;h3&gt;The Pattern&lt;/h3&gt;&lt;br /&gt;For those not familiar with it, the module pattern is basically:&lt;ul&gt;&lt;li&gt;Use an enclosing function to provide scope&lt;/li&gt;&lt;li&gt;Use named functions within your function&lt;/li&gt;&lt;li&gt;Export the ones you want to have as public methods by returning them from the function (usually as an object hash)&lt;/li&gt;&lt;/ul&gt;E.g., something like this:&lt;br /&gt;&lt;pre&gt;var CoolModule = (function() {&lt;br /&gt;    function foo() { ... }&lt;br /&gt;    function bar() { ... }&lt;br /&gt;    function cool() { ... }&lt;br /&gt;&lt;br /&gt;    return {foo: foo, bar: bar};&lt;br /&gt;})();&lt;/pre&gt;The anonymous function is the scoping function, which we define and then run immediately, assigning its return value to the &lt;code&gt;CoolModule&lt;/code&gt; variable. We end up with a &lt;code&gt;CoolModule&lt;/code&gt; object with the properties &lt;code&gt;foo&lt;/code&gt; and &lt;code&gt;bar&lt;/code&gt; that refer to named functions with the same names. Note that in this example, I did not include &lt;code&gt;cool&lt;/code&gt; in the returned object hash. So what's &lt;code&gt;cool&lt;/code&gt; for?&lt;br /&gt;&lt;br /&gt;The &lt;code&gt;cool&lt;/code&gt; function is accessible anywhere within the scoping function, but no where outside of it. So &lt;code&gt;foo&lt;/code&gt; can use it, as can &lt;code&gt;bar&lt;/code&gt;, but nothing else can. It's a truly private function for the &lt;code&gt;CoolModule&lt;/code&gt; module. That's already really useful, but we can also apply it to classes:&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Defining Classes&lt;/h3&gt;&lt;br /&gt;Okay, so let's look at building a class that way. Most toolkits provide some means of creating a "class" based on an object hash of methods. For instance, using Prototype's &lt;code&gt;Class.create&lt;/code&gt;, we can define a class like so:&lt;br /&gt;&lt;pre&gt;var Thingy = Class.create({&lt;br /&gt;&lt;br /&gt;    initialize: function(name) {&lt;br /&gt;        this.name = name;&lt;br /&gt;    },&lt;br /&gt;&lt;br /&gt;    doSomething: function() {&lt;br /&gt;        // ...&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;});&lt;/pre&gt;That passes an object literal with named properties for each of our "methods", which &lt;code&gt;Class.create&lt;/code&gt; uses to produce a "class" for us (well, more technically a constructor function with the given methods as members on the prototype; JavaScript doesn't have classes, of course, it's a &lt;em&gt;prototypical&lt;/em&gt; language&amp;nbsp&amp;mdash; but that's a different subject).&lt;br /&gt;&lt;br /&gt;Defining &lt;code&gt;Thingy&lt;/code&gt; that way has a problem: All of its functions are anonymous. They're assigned to properties, and those &lt;em&gt;properties&lt;/em&gt; have names, but our &lt;em&gt;functions&lt;/em&gt; do not. This is a problem any time any tool wants to help us out&amp;nbsp;&amp;mdash for instance, if the browser wants to tell us what function an error occurred in, or if a debugger wants to show us the call stack. So we're better off using the module pattern here, like so:&lt;br /&gt;&lt;pre&gt;var Thingy = Class.create((function(){&lt;br /&gt;&lt;br /&gt;    function initialize(name) {&lt;br /&gt;        this.name = name;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function doSomething() {&lt;br /&gt;        // ...&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return {initialize: initialize, doSomething: doSomething};&lt;br /&gt;})());&lt;/pre&gt;Now our functions have proper names. (They can have different names from the properties that reference them, which is sometimes handy, but let's keep them the same for now.)&lt;br /&gt;&lt;br /&gt;Doing that gives us a truly private scope (our anonymous function), which surely helps with giving us truly private methods, right?&lt;br /&gt;&lt;br /&gt;Right.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Class Methods&lt;/h3&gt;&lt;br /&gt;You remember that &lt;code&gt;cool&lt;/code&gt; function from earlier, the one we defined but didn't export. The easiest and most obvious benefit we get from our scoping function is that we immediately have class methods with no need for any other work: We just define a function and don't export it in the return value. It's available to all of our other functions, but it's completely closed off from the outside. It's not tied to any instance, but class methods are quite useful things.&lt;br /&gt;&lt;pre&gt;var Thingy = Class.create((function(){&lt;br /&gt;&lt;br /&gt;    function initialize(name) {&lt;br /&gt;        this.name = name;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function doSomething(param) {&lt;br /&gt;        var transmogrified = transmogrify(param);&lt;br /&gt;        // ...&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function transmogrify(str) {&lt;br /&gt;        return str.toUpperCase();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return {initialize: initialize, doSomething: doSomething};&lt;br /&gt;})());&lt;/pre&gt;Our public method &lt;code&gt;doSomething&lt;/code&gt; uses our private class method &lt;code&gt;transmogrify&lt;/code&gt; to do something to its parameter, presumably something other methods will also need to do but which shouldn't be a public feature of the class. Very handy!&lt;br /&gt;&lt;br /&gt;But can this help us get private instance methods, too, without massive memory overhead?&lt;br /&gt;&lt;br /&gt;Yup. Remember that &lt;a href='http://blog.niftysnippets.org/2008/03/mythical-methods.html'&gt;JavaScript doesn't have methods&lt;/a&gt;, it has &lt;em&gt;functions&lt;/em&gt; (very powerful ones). And how a function falls into our somewhat inappropriate class-based terminology ("function", "instance method", "class method") depends entirely on how it's called; there's nothing intrinsic to the function that makes it one of those things. So if we have truly private class methods, that means we also have truly private instance methods, it's just how we call them. In particular, to get an instance method, all we do is call it in a way that we set its context (its "&lt;code&gt;this&lt;/code&gt;" value). JavaScript provides three ways to do that:&lt;ol&gt;&lt;li&gt;By assigning it to a property on an object, and then calling it via method notation: &lt;code&gt;obj.method()&lt;/code&gt;&lt;/li&gt;&lt;li&gt;By using &lt;code&gt;Function#call&lt;/code&gt;&lt;/li&gt;&lt;li&gt;By using &lt;code&gt;Function#apply&lt;/code&gt;&lt;/li&gt;&lt;/ol&gt;The only difference between the last two is how they accept arguments to pass to the function.&lt;br /&gt;&lt;br /&gt;Based on the above, so far, I've come up with four ways to get truly private instance methods (at least two of which I know I've seen elsewhere [one after I came up with it, one before]; and I can't imagine the other two are really original, either, even if &lt;em&gt;I&lt;/em&gt; haven't seen them). They have varying trade-offs between speed, convenience, and maintainability.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Calling All Instances&lt;/h3&gt;&lt;br /&gt;The first way is really quite obvious: Using &lt;code&gt;Function#call&lt;/code&gt; or &lt;code&gt;Function#apply&lt;/code&gt;. Here's an example:&lt;br /&gt;&lt;pre&gt;var Thingy = Class.create((function(){&lt;br /&gt;&lt;br /&gt;    function initialize(name) {&lt;br /&gt;        this.name = name;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function doPublic() {&lt;br /&gt;        doPrivate.call(this);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function doPrivate() {&lt;br /&gt;        alert(this.name);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return {&lt;br /&gt;        initialize: initialize,&lt;br /&gt;        doPublic: doPublic&lt;br /&gt;    };&lt;br /&gt;})());&lt;br /&gt;var t = new Thing("Fred");&lt;br /&gt;t.doPublic(); // Alerts "Fred" via private instance method&lt;/pre&gt;Our &lt;code&gt;doPublic&lt;/code&gt; function calls our &lt;code&gt;doPrivate&lt;/code&gt; function via &lt;code&gt;Function#call&lt;/code&gt;; our truly private instance method then shows the name of the &lt;code&gt;Thingy&lt;/code&gt;. &lt;code&gt;doPrivate&lt;/code&gt;'s context ("&lt;code&gt;this&lt;/code&gt;") is set to the instance, and so it has normal access to the instance's properties, including name. Voil&amp;agrave;! (Sort of.)&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Going Procedural&lt;/h3&gt;&lt;br /&gt;If, like me, you thought "&lt;code&gt;doPrivate.call(this)&lt;/code&gt;" looked vaguely familiar, we may have something in common: A background in procedural languages. Using &lt;code&gt;Function#call&lt;/code&gt; to call a function and set its context looks &lt;em&gt;very&lt;/em&gt; much like just calling a function and passing it a parameter. So even though it's cheating a bit, let's just give a nod to procedural programming here:&lt;br /&gt;&lt;pre&gt;var Thingy = Class.create((function(){&lt;br /&gt;&lt;br /&gt;    function initialize(name) {&lt;br /&gt;        this.name = name;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function doPublic() {&lt;br /&gt;        doPrivate(this);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function doPrivate(self) {&lt;br /&gt;        alert(self.name);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return {&lt;br /&gt;        initialize: initialize,&lt;br /&gt;        doPublic: doPublic&lt;br /&gt;    };&lt;br /&gt;})());&lt;br /&gt;var t = new Thing("Fred");&lt;br /&gt;t.doPublic(); // Alerts "Fred"&lt;/pre&gt;Here, we just have &lt;code&gt;doPublic&lt;/code&gt; call &lt;code&gt;doPrivate&lt;/code&gt; in a procedural fashion, passing in the "&lt;code&gt;this&lt;/code&gt;" reference. Since there are no private properties in JavaScript, &lt;code&gt;doPrivate&lt;/code&gt; has access to just as much information as it did when called in a more instance-like way.&lt;br /&gt;&lt;br /&gt;Okay, but really the holy grail has to be calling the method in the "normal" way: &lt;code&gt;this.method()&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Leveraging Prototypes&lt;/h3&gt;&lt;br /&gt;As you probably know, when an object is created via a constructor function, its prototype gets set to the prototype property of the constructor function. All of the members on that prototype are inherited by the object. They're not copied, they're &lt;em&gt;inherited&lt;/em&gt;. That opens the door to a means of getting the holy grail syntax with truly private methods, but at a cost: What if we create a new object with "&lt;code&gt;this&lt;/code&gt;" as its prototype? Then we can put the private methods on it, and no one else can see them. Well, this does work, but the costs are pretty high. Let's walk through it.&lt;br /&gt;&lt;br /&gt;First, how do we create a new object and assign "&lt;code&gt;this&lt;/code&gt;" as its prototype? Well that part's actually quite easy: We just have a constructor function lying around, set its &lt;code&gt;prototype&lt;/code&gt; property to the instance we want to be the prototype, create a new instance with it, and then restore the constructor's prototype (just to be tidy, we shouldn't keep a reference to the other instance anywhere). (Some browsers let us directly manipulate the prototype of an actual object via a &lt;code&gt;__proto__&lt;/code&gt; property, but others don't and it hasn't been standardized, so we'll stick to the constructor way.) Here's what that looks like:&lt;br /&gt;&lt;pre&gt;var Helper = (function() {&lt;br /&gt;&lt;br /&gt;    // A factory for setting up our private instances&lt;br /&gt;    function factory() {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Our public makePrivate function&lt;br /&gt;    function makePrivate(instance, privateMethods) {&lt;br /&gt;        var rv, name;&lt;br /&gt;&lt;br /&gt;        // Set the prototype of our factory&lt;br /&gt;        factory.prototype = instance;&lt;br /&gt;&lt;br /&gt;        // Get our private instance&lt;br /&gt;        rv = new factory();&lt;br /&gt;&lt;br /&gt;        // Reset the factory prototype (just to be tidy)&lt;br /&gt;        factory.prototype = Object.prototype;&lt;br /&gt;&lt;br /&gt;        // Copy over the private methods&lt;br /&gt;        for (name in privateMethods) {&lt;br /&gt;            rv[name] = privateMethods[name];&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Done&lt;br /&gt;        return rv;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Publish the "makePrivate" function&lt;br /&gt;    return {makePrivate: makePrivate};&lt;br /&gt;})();&lt;/pre&gt;And we can use it like this:&lt;br /&gt;&lt;pre&gt;var Thingy = Class.create((function() {&lt;br /&gt;    var privateMethods;&lt;br /&gt;&lt;br /&gt;    // The private methods for our class&lt;br /&gt;    privateMethods = {&lt;br /&gt;        doPrivate: doPrivate&lt;br /&gt;    };&lt;br /&gt;&lt;br /&gt;    function initialize(name) {&lt;br /&gt;        this.name = name;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function doPublic() {&lt;br /&gt;        var self;&lt;br /&gt;&lt;br /&gt;        // Get a version of "this" that has our private stuff&lt;br /&gt;        self = Helper.makePrivate(this, privateMethods);&lt;br /&gt;&lt;br /&gt;        // Use it&lt;br /&gt;        self.doPrivate();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function doPrivate() {&lt;br /&gt;        alert(this.name);&lt;br /&gt;    }&lt;br /&gt;    return {&lt;br /&gt;        initialize: initialize,&lt;br /&gt;        doPublic: doPublic&lt;br /&gt;    };&lt;br /&gt;&lt;br /&gt;})());&lt;br /&gt;var t = new Thingy("Fred");&lt;br /&gt;t.doPublic(); // Alerts "Fred"&lt;/pre&gt;Leaving aside the setup overhead, we've reached the holy grail, right?&lt;br /&gt;&lt;br /&gt;Hmmm, not quite. This is all very well for if we &lt;em&gt;read&lt;/em&gt; properties, but if we &lt;em&gt;write&lt;/em&gt; them, we run into a bit of a problem: Setting a property on our private instance will only set it there, not on its prototype, so when we discard our private instance (as we do at the end of &lt;code&gt;doPublic&lt;/code&gt;), any changes are lost with it&amp;nbsp;&amp;mdash e.g., if &lt;code&gt;doPrivate&lt;/code&gt; changes anything:&lt;br /&gt;&lt;pre&gt;    function doPrivate() {&lt;br /&gt;        alert(this.name);&lt;br /&gt;        this.name = this.name.toUpperCase();&lt;br /&gt;    }&lt;/pre&gt;...the changes are lost:&lt;br /&gt;&lt;pre&gt;var t = new Thing("Fred");&lt;br /&gt;t.doPublic();  // Alerts "Fred"&lt;br /&gt;alert(t.name); // Also alerts "Fred", not "FRED"&lt;/pre&gt;Not good. Now, your first thought (if you're like me) is that all we need is a method that sets the property on the underlying instance, and all private methods need to be sure to use it. But no, if you think about it a little longer, you realize that not only the private methods but also the public ones have to use it (since if we call them, &lt;code&gt;this&lt;/code&gt; will refer to our private instance).  Worse, not only your own methods, but all superclass methods also have to use it. Now, if you're an adherent to the philosophy that all property access should be through getters and setters &lt;em&gt;anyway&lt;/em&gt;, that will work, and your setter would look like this:&lt;br /&gt;&lt;pre&gt;function setName(name) {&lt;br /&gt;    var inst = this.hasOwnProperty('_original')&lt;br /&gt;               ? this._original&lt;br /&gt;               : this;&lt;br /&gt;    inst.name = name;&lt;br /&gt;}&lt;/pre&gt;...assuming you've modified &lt;code&gt;makePrivate&lt;/code&gt; to store the original instance on the private instance as the property &lt;code&gt;_original&lt;/code&gt;. If you're not an adherent of that getter/setter philosophy, though (and I've never seen any substantial JavaScript written by anyone who was), it's a problem.&lt;br /&gt;&lt;br /&gt;There's another way: Just as we have to do something when we "go private", we just add a step for when we're "done" with the private thing. The "done" function takes any properties explicitly assigned to the private instance and copies them to the original. Like so:&lt;br /&gt;&lt;pre&gt;var Helper = (function() {&lt;br /&gt;&lt;br /&gt;    // A factory for setting up our private instances&lt;br /&gt;    function factory() {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Our public enterPrivate function&lt;br /&gt;    function enterPrivate(instance, methods) {&lt;br /&gt;        var rv, name;&lt;br /&gt;&lt;br /&gt;        // Set the prototype of our factory&lt;br /&gt;        factory.prototype = instance;&lt;br /&gt;&lt;br /&gt;        // Get our private instance&lt;br /&gt;        rv = new factory();&lt;br /&gt;&lt;br /&gt;        // Restore the factory prototype (just to be tidy)&lt;br /&gt;        factory.prototype = Object.prototype;&lt;br /&gt;&lt;br /&gt;        // Remember the private methods and the original&lt;br /&gt;        // object, we'll want them for later&lt;br /&gt;        rv._privateMethods = methods;&lt;br /&gt;        rv._original = instance;&lt;br /&gt;&lt;br /&gt;        // Copy over the private methods&lt;br /&gt;        for (name in methods) {&lt;br /&gt;            rv[name] = methods[name];&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Done&lt;br /&gt;        return rv;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Our public exitPrivate function&lt;br /&gt;    function exitPrivate(instance) {&lt;br /&gt;        var name, original;&lt;br /&gt;&lt;br /&gt;        original = instance._original;&lt;br /&gt;        for (name in instance) {&lt;br /&gt;            if (name != '_original' &amp;&amp;&lt;br /&gt;                instance.hasOwnProperty(name) &amp;&amp;&lt;br /&gt;                !(name in instance._privateMethods)&lt;br /&gt;               ) {&lt;br /&gt;                original[name] = instance[name];&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;        return original;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Export our public functions&lt;br /&gt;    return {enterPrivate: enterPrivate, exitPrivate: exitPrivate};&lt;br /&gt;})();&lt;/pre&gt;..and then we can use it like this:&lt;br /&gt;&lt;pre&gt;var Thingy = Class.create((function() {&lt;br /&gt;    var privateMethods;&lt;br /&gt;&lt;br /&gt;    // The private methods for our class&lt;br /&gt;    privateMethods = {&lt;br /&gt;        doPrivate: doPrivate&lt;br /&gt;    };&lt;br /&gt;&lt;br /&gt;    function initialize(name) {&lt;br /&gt;        this.name = name;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function doPrivate() {&lt;br /&gt;        alert(this.name);&lt;br /&gt;        this.name = this.name.toUpperCase();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function doPublic(name) {&lt;br /&gt;        var self;&lt;br /&gt;&lt;br /&gt;        // Public-&gt;Private boundary, need to "enter" private mode&lt;br /&gt;        self = Helper.enterPrivate(this, privateMethods);&lt;br /&gt;&lt;br /&gt;        // ...do things...&lt;br /&gt;        self.doPrivate();&lt;br /&gt;&lt;br /&gt;        // Private-&gt;Public boundary, need to "exit" private mode&lt;br /&gt;        Helper.exitPrivate(self);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return {&lt;br /&gt;        initialize: initialize,&lt;br /&gt;        doPublic: doPublic&lt;br /&gt;    };&lt;br /&gt;&lt;br /&gt;})());&lt;br /&gt;var t = new Thing("Fred");&lt;br /&gt;t.doPublic();  // Alerts "Fred"&lt;br /&gt;alert(t.name); // Also alerts "FRED"&lt;/pre&gt;Now we're safe from losing our updated properties when we're done with the private instance (provided we don't forget to call &lt;code&gt;exitPrivate&lt;/code&gt;!).&lt;br /&gt;&lt;br /&gt;Naturally the &lt;code&gt;enterPrivate&lt;/code&gt; and &lt;code&gt;exitPrivate&lt;/code&gt; functions mean we incur a lot of runtime overhead; but at least once we're "in," we're able to do things with completely normal syntax and it Just Works. And using prototypes in this way is very cool. Unfortunately, though, all of that copying back and forth and object instantiation really does kill performance.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Enh, Forget Prototypes&lt;/h3&gt;&lt;br /&gt;If we're going to be doing a lot of copying of things when "entering" and "exiting" private code, we can try to improve performance by ditching object instantiation and fancy prototype stuff and just mucking about with the original instance directly:&lt;br /&gt;&lt;pre&gt;var Helper = (function() {&lt;br /&gt;&lt;br /&gt;    // Our public enterPrivate function&lt;br /&gt;    function enterPrivate(instance, methods) {&lt;br /&gt;        var old, name;&lt;br /&gt;&lt;br /&gt;        old = {};&lt;br /&gt;        for (name in methods) {&lt;br /&gt;            if (instance.hasOwnProperty(name)) {&lt;br /&gt;                old[name] = instance[name];&lt;br /&gt;            }&lt;br /&gt;            instance[name] = methods[name];&lt;br /&gt;        }&lt;br /&gt;        if (instance.hasOwnProperty('_oldStuff') &amp;&amp; !('_oldStuff' in old)) {&lt;br /&gt;            old._oldStuff = instance._oldStuff;&lt;br /&gt;        }&lt;br /&gt;        if (instance.hasOwnProperty('_methods') &amp;&amp; !('_methods' in old)) {&lt;br /&gt;            old._methods = instance._methods;&lt;br /&gt;        }&lt;br /&gt;        instance._methods = methods;&lt;br /&gt;        instance._oldStuff = old;&lt;br /&gt;        return instance;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Our public exitPrivate function&lt;br /&gt;    function exitPrivate(instance) {&lt;br /&gt;        var methods, old, name;&lt;br /&gt;&lt;br /&gt;        methods = instance._methods;&lt;br /&gt;        delete instance._methods;&lt;br /&gt;        old = instance._oldStuff;&lt;br /&gt;        delete instance._oldStuff;&lt;br /&gt;&lt;br /&gt;        for (name in methods) {&lt;br /&gt;            delete instance[name];&lt;br /&gt;        }&lt;br /&gt;        for (name in old) {&lt;br /&gt;            instance[name] = old[name];&lt;br /&gt;        }&lt;br /&gt;        return instance;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Export our public functions&lt;br /&gt;    return {enterPrivate: enterPrivate, exitPrivate: exitPrivate};&lt;br /&gt;})();&lt;/pre&gt;And then we use it like so:&lt;br /&gt;&lt;pre&gt;var Thingy = Class.create((function() {&lt;br /&gt;    var privateMethods;&lt;br /&gt;&lt;br /&gt;    // Our private methods&lt;br /&gt;    privateMethods = {&lt;br /&gt;        doPrivate: doPrivate1&lt;br /&gt;    };&lt;br /&gt;&lt;br /&gt;    function initialize(name) {&lt;br /&gt;        this.name = name;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function doPrivate() {&lt;br /&gt;        alert(this.name);&lt;br /&gt;        this.name = this.name.toUpperCase();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function doPublic(name) {&lt;br /&gt;&lt;br /&gt;        // Public-&gt;Private boundary, need to "enter" private mode&lt;br /&gt;        Helper.enterPrivate(this, privateMethods);&lt;br /&gt;&lt;br /&gt;        // Do some stuff&lt;br /&gt;        this.doPrivate();&lt;br /&gt;&lt;br /&gt;        // Private-&gt;Public boundary, need to "exit" private mode&lt;br /&gt;        Helper.exitPrivate(this);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return {&lt;br /&gt;        initialize: initialize,&lt;br /&gt;        doPublic: doPublic&lt;br /&gt;    };&lt;br /&gt;&lt;br /&gt;})());&lt;br /&gt;var t = new Thingy();&lt;br /&gt;t.doPublic();  // Alerts "Fred"&lt;br /&gt;alert(t.name); // Alerts "FRED"&lt;/pre&gt;Well, like the prototype solution, it &lt;em&gt;works&lt;/em&gt;, but it has some pretty ugly performance.&lt;br /&gt;&lt;br /&gt;I should also mention that both the prototype and the overlay solutions will wreak havoc if you have a subclass with a private method that has the same name as a public method on a base class. You Have Been Warned.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Performance Matters&lt;/h3&gt;&lt;br /&gt;Okay, so bringing it all together, we've looked at four mechanisms (one with two variations) that avoid the problem of creating a copy of every method for every instance. We've mentioned that a couple of them incur quite a bit of overhead. But...how &lt;em&gt;much&lt;/em&gt; overhead, really? I mean, do they cut speed by 10%, 20%, 30%? Enquiring minds want to know!&lt;br /&gt;&lt;br /&gt;Well, I put together basic test for six options:&lt;ol&gt;&lt;li&gt;Don't worry, just use public methods and tell people not to call them (e.g., by naming convention or some such).&lt;/li&gt;&lt;li&gt;Use the &lt;code&gt;Function#call&lt;/code&gt; variety.&lt;/li&gt;&lt;li&gt;Use procedural programming.&lt;/li&gt;&lt;li&gt;Use the prototype trick, with an "exit" that finds and copies back properties set since going private.&lt;/li&gt;&lt;li&gt;Use the prototype trick, being careful to always use "set" methods.&lt;/li&gt;&lt;li&gt;Using the overlay trick (updating the instance in place).&lt;/li&gt;&lt;/ol&gt;You can grab the source or run it for yourself &lt;a href='http://www.crowdersoftware.com/bimg/privatespeed.html'&gt;here&lt;/a&gt;; here's the skinny from some popular browsers on Windows:&lt;br /&gt;&lt;br /&gt;Firefox:&lt;br /&gt;&lt;br /&gt;&lt;img src='http://www.crowdersoftware.com/bimg/firefox3.5.png'&gt;&lt;br /&gt;&lt;br /&gt;IE7 (I don't have IE8 on my little netbook):&lt;br /&gt;&lt;br /&gt;&lt;img src='http://www.crowdersoftware.com/bimg/ie7.png'&gt;&lt;br /&gt;&lt;br /&gt;Chrome:&lt;br /&gt;&lt;br /&gt;&lt;img src='http://www.crowdersoftware.com/bimg/chrome2.png'&gt;&lt;br /&gt;&lt;br /&gt;Safari:&lt;br /&gt;&lt;br /&gt;&lt;img src='http://www.crowdersoftware.com/bimg/safari4.png'&gt;&lt;br /&gt;&lt;br /&gt;Opera:&lt;br /&gt;&lt;br /&gt;&lt;img src='http://www.crowdersoftware.com/bimg/opera10.png'&gt;&lt;br /&gt;&lt;br /&gt;As you can see, our "holy grail" solutions (the last three in each set) perform abysmally. It varies by browser quite a bit, but across the board they're really dramatically slow. Mind you, my implementations of them may well be sub-optimal (I dashed them off), but the implementation would have to improve &lt;em&gt;hugely&lt;/em&gt; to make performance acceptable. Combine that with the inevitable bugs related to forgetting an "enter" or "exit" call, and I think you'd be hard-pressed to find a good use case for them.&lt;br /&gt;&lt;br /&gt;The results for the first three are interesting. Chrome and IE7 are apparently faster at finding a function object by looking at the properties of the instance than they are by looking on the scope chain; Firefox, Safari, and Opera are faster when we ask for the function from the scope chain. The theme that definitely emerges, though, is that if performance matters to you, just use public methods people are supposed to leave alone, or make your truly-private functions procedural (although the cost of calling them via &lt;code&gt;Function#call&lt;/code&gt; instead isn't &lt;em&gt;very&lt;/em&gt; high, if you really prefer that).&lt;br /&gt;&lt;br /&gt;As a side-note, although I didn't test it, I would expect Crockford's pattern (closures for each instance, each instance gets its own copy of all functions) to have call times in line with the procedural timings above, as that's effectively what it does, just at the instance rather than class level.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Does Performance Matter?&lt;/h3&gt;&lt;br /&gt;So the next question is, okay, so some of the mechanisms impact call time by huge amounts&amp;nbsp;&amp;mdash more than an order of magnitude in some cases. But...does it matter? Computers are crazy fast these days, right?&lt;br /&gt;&lt;br /&gt;Chrome, the fastest in this test (and many others) varied from performing a private call in 0.000003418396717245264495027600135 seconds (three hundreths of a millisecond) at its fastest to doing it in 0.00013514974591847767326197426749 seconds (1.3 milliseconds) at its slowest. IE7, the slowest in this test (and many others) varied from 0.000092537755404204915605567071365 seconds (9/10ths of a millisecond) per call down to 0.48923679060665362035225048924 seconds (just under half a second) per call. And these tests were done on a &lt;a href='http://en.wikipedia.org/wiki/Samsung_NC10'&gt;netbook-class machine&lt;/a&gt; (wonderful little unit, don't let the picture in the WP article put you off, it's a color-balance problem in the photo).&lt;br /&gt;&lt;br /&gt;Everyone has to make their own decision about this. My stake in the ground is that it does matter, yes, particularly as long as the majority of web users are still using the slowest web browser out of the big players: IE. In our modern web applications, a click by a user might kick off 10-20 underlying JavaScript function calls (at least!). If we say 10 and half of those are "private," it makes the difference between IE in responding in no less than 5 milliseconds to taking at least 2.4 seconds. That's a big drop in user-perceived performance. So for my money, within an application I probably won't worry and will just make things public; in &lt;em&gt;library&lt;/em&gt; work (either internal libraries used by multiple apps, or publicly-released libraries) I'll probably go with truly private class methods and pass in instances when necessary (e.g., procedural use).&lt;br /&gt;&lt;br /&gt;Whatever you end up doing, I hope this roundup of private method options is useful.&lt;br /&gt;&lt;br /&gt;Happy coding,&lt;br /&gt;&lt;br /&gt;-- T.J.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-4004866189761444001?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/uHGm3tCTNp0" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/uHGm3tCTNp0/private-methods-in-javascript.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2009/09/private-methods-in-javascript.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-4742726851690218350</guid><pubDate>Wed, 09 Sep 2009 16:19:00 +0000</pubDate><atom:updated>2010-02-03T08:52:00.784Z</atom:updated><title>Simple, Efficient Supercalls in JavaScript</title><description>In this post, I'll be outlining a simple means of doing supercalls in JavaScript without causing unnecessary runtime overhead, running into maintenance issues, or falling afoul of the new "strict" mode of ECMAScript 5.&lt;br /&gt;&lt;h3&gt;The Short Version&lt;/h3&gt;&lt;br /&gt;The mechanism in brief is:&lt;ul&gt;&lt;li&gt;Have a "make a class" function (most libraries do).&lt;/li&gt;&lt;li&gt;In that function, detect that a subclass is overriding a superclass function and, if so, put a reference to the superclass function on the subclass function instance as a property.&lt;/li&gt;&lt;li&gt;To call a superclass function from a subclass function, authors use &lt;code&gt;Function#call&lt;/code&gt; or &lt;code&gt;Function#apply&lt;/code&gt; on the &lt;code&gt;$super&lt;/code&gt; property of the subclass function instance (being sure to get the function directly, &lt;em&gt;not&lt;/em&gt; via &lt;code&gt;this&lt;/code&gt;). This is simplest and fastest with named functions, but possible with anonymous ones too.&lt;/li&gt;&lt;li&gt;Allow for mixins, if you're into that sort of thing (and why not, they're cool).&lt;/li&gt;&lt;/ul&gt;That's it. Dead simple, and dramatically more efficient than the wrapping subclass functions in closures, doing function decompilation (which has never been standardized), etc. It leads to more maintainable (and readable) code than having subclasses refer to their parents by name, and even encourages the use of named functions, which is a good idea for lots of other reasons.&lt;br /&gt;&lt;br /&gt;Okay, on to the details, including a full sample implementation, and discussion around the various choices and issues.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;What Lead To This&lt;/h3&gt;&lt;br /&gt;Let me step back a moment and explain how this came about. I have a project requiring a fair bit of server-side JavaScript and also object hierarchy. Not wanting to use "raw" JavaScript hierarchy or roll my own, I naturally reached for my favorite JavaScript library, &lt;a href='http://prototypejs.org'&gt;Prototype&lt;/a&gt;, since this is one of the many things it does. Now, Prototype is currently tied to web browsers (something the core team are fixing even as I write this), so I figured until Prototype 2 comes out, I'd just copy the relevant parts (the Class class) and then switch to using Prototype 2 later when it comes out.&lt;br /&gt;&lt;br /&gt;So I started doing that, but then remembered that I'm not a big fan of how Prototype does supercalls&amp;nbsp;&amp;mdash; you know, when a subclass overrides a superclass method but then wants to call the superclass's version. My initial issue was mostly with the API it provides (the superclass's function is a special parameter to the subclass function, which seems odd to me), but as I was copying &lt;code&gt;Class&lt;/code&gt; over and reading through the code, and realized that what Prototype does under the covers to make supercalls work (which includes function decompilation, wrapping in closures, and creating a new function on &lt;em&gt;every&lt;/em&gt; call to a supercall-enabled method) is an awful lot of runtime overhead.&lt;br /&gt;&lt;br /&gt;So I thought: "Surely I could just tweak this a bit to..." Yes, that's right, I fell right into the anti-pattern of reinventing the wheel. But I'm glad I did, because it taught me a lot I didn't know before, and lead me (with some help from my friends) to come up with this dead-simple mechanism for supercalls. (Caveat: I can't imagine this mechanism is unique, but it was new to me.)&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Hierarchy In JavaScript&lt;/h3&gt;&lt;br /&gt;I won't go into a thorough discussion of hierarchy in JavaScirpt, but suffice to say that whether you use Prototype or something else, it probably provides something that lets you create "classes" by calling a special helper function, passing in an object that has properties referencing the instance methods you want in your class, and getting back a constructor you can call:&lt;br /&gt;&lt;pre&gt;// Defining the class&lt;br /&gt;var SpiffyClass = Helper.makeClass({&lt;br /&gt;    initialize: function() {&lt;br /&gt;        // ...initialize an instance...&lt;br /&gt;    },&lt;br /&gt;    nifty: function() {&lt;br /&gt;        // ...do something nifty...&lt;br /&gt;    }&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;// Creating an instance&lt;br /&gt;var spiffy = new SpiffyClass();&lt;/pre&gt;This pattern&amp;nbsp;&amp;mdash; passing an object literal into a helper function&amp;nbsp;&amp;mdash; has been very successful in recent years, and for good reason: It's terse but expressive. (There's a problem with it we'll come back to later, but it gets the job done.)&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Inside The Helper&lt;/h3&gt;&lt;br /&gt;Let's look into the helper to see what it's doing. Here's a first-cut on what &lt;code&gt;Helper.makeClass&lt;/code&gt; might look like&amp;nbsp;&amp;mdash; the code comments basically tell the story (download it &lt;a href='http://www.crowdersoftware.com/bimg/supercalls1.js'&gt;here&lt;/a&gt; if the below is awkward to read; I hate Blogger!):&lt;br /&gt;&lt;pre&gt;// Take I, doesn't help with supercalls.&lt;br /&gt;// Inspired by Prototype's Class class (http://prototypejs.org)&lt;br /&gt;// Copyright (C) 2009 by T.J. Crowder&lt;br /&gt;// Licensed under the Creative Commons Attribution License 2.0 (UK)&lt;br /&gt;// http://creativecommons.org/licenses/by/2.0/uk/&lt;br /&gt;var Helper = (function(){&lt;br /&gt;&lt;br /&gt;    // Build and return a constructor; we do this with a separate function&lt;br /&gt;    // to minimize what the new constructor (a closure) closes over.&lt;br /&gt;    function makeConstructor() {&lt;br /&gt;&lt;br /&gt;        // Here's our basic constructor function (each class gets its own, a&lt;br /&gt;        // new one of these is created every time makeConstructor is called).&lt;br /&gt;        function ctor() {&lt;br /&gt;            // Call the initialize method&lt;br /&gt;            this.initialize.apply(this, arguments);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        return ctor;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // This function is used when a class doesn't have its own initialize&lt;br /&gt;    // function; since it does nothing and can only appear on base classes,&lt;br /&gt;    // all instances can share it.&lt;br /&gt;    function defaultInitialize() {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // makeClass: Our public "make a class" function.&lt;br /&gt;    // Arguments:&lt;br /&gt;    // - base: An optional constructor for the base class.&lt;br /&gt;    // - ...:  One or more specification objects containing properties to&lt;br /&gt;    //         put on our class as members. If a property is defined by more&lt;br /&gt;    //         than one specification object, the last in the list wins.&lt;br /&gt;    // Returns:&lt;br /&gt;    //     A constructor function for instances of the class.&lt;br /&gt;    //&lt;br /&gt;    // Typical use will be just one specification object, but allow for more&lt;br /&gt;    // in case the author is drawing members from multiple locations.&lt;br /&gt;    function makeClass() {&lt;br /&gt;        var base,       // Our base class (constructor function), if any&lt;br /&gt;            argsIndex,  // Index of first unused argument in 'arguments'&lt;br /&gt;            ctor,       // The constructor function we create and return&lt;br /&gt;            members,    // Each members specification object&lt;br /&gt;            name;       // Each name in 'members'&lt;br /&gt;&lt;br /&gt;        // We use this index to keep track of the arguments we've consumed&lt;br /&gt;        argsIndex = 0;&lt;br /&gt;&lt;br /&gt;        // Do we have a base?&lt;br /&gt;        if (typeof arguments[argsIndex] == 'function') {&lt;br /&gt;            // Yes&lt;br /&gt;            base = arguments[argsIndex++];&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Get our constructor&lt;br /&gt;        ctor = makeConstructor();&lt;br /&gt;&lt;br /&gt;        // Apply the base class if any by assigning an instance of it to&lt;br /&gt;        // our constructor's prototype&lt;br /&gt;        if (base) {&lt;br /&gt;            ctor.prototype = new base();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Set our constructor property so "this.constructor" resolves&lt;br /&gt;        // correctly&lt;br /&gt;        ctor.prototype.constructor = ctor;&lt;br /&gt;&lt;br /&gt;        // Assign the members from the specification object(s) to the prototype&lt;br /&gt;        // Again, typically there's only spec object, but allow for more&lt;br /&gt;        while (argsIndex &lt; arguments.length) {&lt;br /&gt;            // Get this specification object&lt;br /&gt;            members = arguments[argsIndex++];&lt;br /&gt;&lt;br /&gt;            // Copy its members&lt;br /&gt;            for (name in members) {&lt;br /&gt;                ctor.prototype[name] = members[name];&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // If there's no initialize function, provide one&lt;br /&gt;        if (!('initialize' in ctor.prototype)) {&lt;br /&gt;            // Note that this can only happen in base classes; in a derived&lt;br /&gt;            // class, the check above will find the base class's version if the&lt;br /&gt;            // subclass didn't define one.&lt;br /&gt;            ctor.prototype.initialize = defaultInitialize;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Return the constructor&lt;br /&gt;        return ctor;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Return our public members&lt;br /&gt;    return {makeClass: makeClass};&lt;br /&gt;})();&lt;/pre&gt;So far, nothing new, this is just the kind of thing you'll find in most libraries.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Supercalls&lt;/h3&gt;&lt;br /&gt;The helper as written is already really useful:&lt;br /&gt;&lt;pre&gt;var Parent = Helper.makeClass({&lt;br /&gt;    nifty: function() {&lt;br /&gt;        return "Nifty!";&lt;br /&gt;    }&lt;br /&gt;});&lt;br /&gt;var Child = Helper.makeClass(Parent, {&lt;br /&gt;    spiffy: function() {&lt;br /&gt;        return "Spiffy!";&lt;br /&gt;    }&lt;br /&gt;});&lt;br /&gt;var c = new Child();&lt;br /&gt;alert(c.nifty());  // Alerts "Nifty!" using Parent#nifty&lt;br /&gt;alert(c.spiffy()); // Alerts "Spiffy!" using Child#spiffy&lt;/pre&gt;But what if we want to override &lt;code&gt;#nifty&lt;/code&gt; in &lt;code&gt;Child&lt;/code&gt; to do some processing on &lt;code&gt;Parent&lt;/code&gt;'s return value? Well, we can do that by going direct to the parent and using &lt;code&gt;Function#call&lt;/code&gt; (or &lt;code&gt;Function#apply&lt;/code&gt;), but the syntax is quite awkward:&lt;br /&gt;&lt;pre&gt;var Child = Helper.makeClass(Parent, {&lt;br /&gt;    nifty: function() {&lt;br /&gt;        var rv = Parent.prototype.nifty.call(this);&lt;br /&gt;        return rv.toUpperCase();&lt;br /&gt;    },&lt;br /&gt;    spiffy: function() {&lt;br /&gt;        return "Spiffy!";&lt;br /&gt;    }&lt;br /&gt;});&lt;br /&gt;var c = new Child();&lt;br /&gt;alert(c.nifty());  // Alerts "NIFTY!"&lt;/pre&gt;That works, but there are a few good reasons not to do it:&lt;ul&gt;&lt;li&gt;It's long-winded, inviting irritating mistakes.&lt;/li&gt;&lt;li&gt;It's makes re-basing a class difficult (every method that does this has that superclass name in it).&lt;/li&gt;&lt;li&gt;It makes moving code between classes difficult (ditto).&lt;/li&gt;&lt;/ul&gt;In short, it's a maintenance problem. Manageable, but a problem. And this is why most libraries try to address it in various ways, often involving adding closures and decompilation and indirection and whatnot. On the "up" side, the above is quite direct and performs very quickly. But what if we could get that directness and speed without getting all of that other stuff, and with brevity and maintainability?&lt;br /&gt;&lt;br /&gt;We can.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;With a Little Help(er) From My Friends&lt;/h3&gt;&lt;br /&gt;Our &lt;code&gt;makeClass&lt;/code&gt; function has all of the information it needs to help us out: It can easily tell when we're overriding a base class function, and it can give us a reference to that function without our having to know the base class name. How? By putting it on our function instance. Remember that functions are first-class objects, we can put properties on them.&lt;br /&gt;&lt;br /&gt;This turns out to be really easy. In &lt;code&gt;makeClass&lt;/code&gt;, when copying the members from the specification object(s) to the new constructor's prototype, if a member we're copying is a function and we have a base and the base value is also a function, we stick it on the override function as &lt;code&gt;$super&lt;/code&gt;. E.g., we replace these lines from earlier:&lt;br /&gt;&lt;pre&gt;for (name in members) {&lt;br /&gt;    ctor.prototype[name] = members[name];&lt;br /&gt;}&lt;/pre&gt;...with:&lt;pre&gt;for (name in members) {&lt;br /&gt;    value = members[name];&lt;br /&gt;    if (base &amp;&amp; typeof value == 'function') {&lt;br /&gt;        baseValue = base.prototype[name];&lt;br /&gt;        if (typeof baseValue == 'function') {&lt;br /&gt;            value.$super = baseValue;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    ctor.prototype[name] = value;&lt;br /&gt;}&lt;/pre&gt;(Also add the 'value' and 'baseValue' declarations at the top.)&lt;br /&gt;&lt;br /&gt;So now we can get at our superclass's function by looking at the &lt;code&gt;$super&lt;/code&gt; property on our own function. But how do we get that? In our &lt;code&gt;Child#nifty&lt;/code&gt; function earlier, say, how do we get to &lt;code&gt;Parent#nifty&lt;/code&gt;? If your first thought (like mine) is &lt;code&gt;this.nifty.$super&lt;/code&gt;, I'm afraid you're not thinking it through&amp;nbsp;&amp;mdash; that will work only for one level of hierarchy, it will fail if anything (say, &lt;code&gt;GrandChild&lt;/code&gt;) derives from &lt;code&gt;Child&lt;/code&gt; and has its own &lt;code&gt;#nifty&lt;/code&gt; function, because with a &lt;code&gt;GrandChild&lt;/code&gt; instance, &lt;code&gt;this.nifty&lt;/code&gt; is always &lt;code&gt;GrandChild#nifty&lt;/code&gt;. If &lt;code&gt;Child#nifty&lt;/code&gt; called &lt;code&gt;this.nifty.$super&lt;/code&gt; in that situation, it would be calling itself, not &lt;code&gt;Parent#nifty&lt;/code&gt;, recursing until the engine gave up on it. So &lt;code&gt;this&lt;/code&gt; is out.&lt;br /&gt;&lt;br /&gt;And here we run into an issue. We want to get at our current function object, but so far we haven't been giving our functions names. They're just anonymous functions we've assigned to properties on objects. The &lt;em&gt;properties&lt;/em&gt; have names, but the functions do not, and we've just concluded we can't use the property (because we can only get to it via &lt;code&gt;this&lt;/code&gt;, and that means it'll always point to the bottommost&amp;nbsp;&amp;mdash; &lt;code&gt;GrandChild&lt;/code&gt;&amp;nbsp;&amp;mdash; function). So now what?&lt;br /&gt;&lt;br /&gt;Well, there is a way, but it's a bit ugly (on a couple of fronts):  &lt;code&gt;arguments.callee&lt;/code&gt;.  The &lt;code&gt;arguments&lt;/code&gt; object, I'm sure you know, is an array-like object defined within functions that contains the arguments passed into the function. That object also has a property on it called &lt;code&gt;callee&lt;/code&gt; that is a reference to the actual function object. So we can get at our super function using &lt;code&gt;arguments.callee.$super&lt;/code&gt;. And like all other functions, we can call it and pass in the value to use as &lt;code&gt;this&lt;/code&gt; by using the &lt;code&gt;Function#call&lt;/code&gt; function. So:&lt;br /&gt;&lt;pre&gt;var Child = Helper.makeClass(Parent, {&lt;br /&gt;    nifty: function() {&lt;br /&gt;        var rv = arguments.callee.$super.call(this); // Blech&lt;br /&gt;        return rv.toUpperCase();&lt;br /&gt;    },&lt;br /&gt;});&lt;br /&gt;alert(c.nifty());  // Alerts "NIFTY!"&lt;/pre&gt;That works, and is more efficient than most other schemes, but it has some issues:&lt;ul&gt;&lt;li&gt;It's long-winded, inviting irritating mistakes (wait, where have I heard that before?)&lt;/li&gt;&lt;li&gt;The new ECMAScript standard, 5th edition, has a "strict" mode in which &lt;code&gt;arguments.callee&lt;/code&gt; (amongst other things) is disallowed (many thanks to &lt;a href='http://twitter.com/jdalton'&gt;John-David Dalton&lt;/a&gt; and &lt;a href='http://thinkweb2.com/projects/prototype/'&gt;Juriy Zaytsev&lt;/a&gt;&amp;nbsp;&amp;mdash; kangax&amp;nbsp;&amp;mdash; for pointing this out to me)&lt;/li&gt;&lt;li&gt;It's slow (although faster than many other ways of doing this), most browsers don't set up &lt;code&gt;arguments.callee&lt;/code&gt; unless you use it, and they're pretty slow at setting it up (thanks again, kangax, for that one)&lt;/li&gt;&lt;/ul&gt;Still, it is functional (outside of strict mode). But what if we could get there another way without those problems?&lt;br /&gt;&lt;br /&gt;You guessed it, we can. And in fact, we get a lot of other benefits when we do.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Named Functions&lt;/h3&gt;&lt;br /&gt;The problem is anonymous functions, and it's not the only problem with them either. Anonymous functions are tools-hostile. Our browsers can't tell us the name of the function in which an error occurred if it's anonymous. Our debuggers can't show us meaningful call stacks with anonymous functions (we just see a lot of question marks, usually). Etc.&lt;br /&gt;&lt;br /&gt;So if the problem is anonymous functions, well, let's just give our functions names! That way, we can use the name directly, since a function's name is defined throughout the scope in which the function is defined (including within the function itself); that's how we usually write recursive functions, after all.&lt;br /&gt;&lt;br /&gt;So when defining classes, how can we give our functions names? One's first thought might be to simply do this:&lt;br /&gt;&lt;pre&gt;var Child = Helper.makeClass(Parent, {&lt;br /&gt;    nifty: function nifty() { // &lt;= PROBLEMATIC&lt;br /&gt;        // ...&lt;br /&gt;    }&lt;br /&gt;});&lt;/pre&gt;In some ways, that should work, but it has ramifications. The name "&lt;code&gt;nifty&lt;/code&gt;" gets defined in the enclosing scope, which in our case above is global&amp;nbsp;&amp;mdash; not a good idea! And it flat out doesn't work with Internet Explorer (or anywhere you're using JScript) or Safari. (For the full story, check out Juriy's excellent &lt;a href='http://yura.thinkweb2.com/named-function-expressions/'&gt;article on the subject&lt;/a&gt;, it's a good read.)&lt;br /&gt;&lt;br /&gt;No, it would be better to contain the scope a bit (not to mention working around bugs), which is easy enough: Wrap it up in a function:&lt;br /&gt;&lt;pre&gt;var Child = Helper.makeClass(Parent, (function(){&lt;br /&gt;    function nifty() { &lt;br /&gt;        // ...&lt;br /&gt;    }&lt;br /&gt;    function spiffy() { &lt;br /&gt;        // ...&lt;br /&gt;    }&lt;br /&gt;    return {&lt;br /&gt;        nifty:  nifty,&lt;br /&gt;        spiffy: spiffy&lt;br /&gt;    };&lt;br /&gt;})());&lt;/pre&gt;That probably wants breaking down a bit:&lt;ul&gt;&lt;li&gt;We define an anonymous function for scoping&lt;/li&gt;&lt;li&gt;Within that scoping function, we define our various methods for &lt;code&gt;Child&lt;/code&gt;&amp;nbsp;&amp;mdash; as named functions&lt;/li&gt;&lt;li&gt;Our function names are in scope throughout the scoping function&lt;/li&gt;&lt;li&gt;Our scoping function returns an object with the properties mapped to our named functions (I added a "spiffy" to this example just to make clear how it works with multiple functions)&lt;/li&gt;&lt;li&gt;We execute the scoping function immediately and pass the result (the object) into &lt;code&gt;makeClass&lt;/code&gt;&lt;/li&gt;&lt;/ul&gt;No scope bleed, no issues with IE or Safari, we're all set.&lt;br /&gt;&lt;br /&gt;So okay, but so far I've been leaving out the good bit&amp;nbsp;&amp;mdash; the supercall in &lt;code&gt;Child#nifty&lt;/code&gt;! Here we go:&lt;br /&gt;&lt;pre&gt;var Child = Helper.makeClass(Parent, (function(){&lt;br /&gt;    function nifty() { &lt;br /&gt;        var rv = nifty.$super.call(this);&lt;br /&gt;        return rv.toUpperCase();&lt;br /&gt;    }&lt;br /&gt;    function spiffy() { &lt;br /&gt;        // ...&lt;br /&gt;    }&lt;br /&gt;    return {&lt;br /&gt;        nifty:  nifty,&lt;br /&gt;        spiffy: spiffy&lt;br /&gt;    };&lt;br /&gt;})());&lt;br /&gt;var c = new Child();&lt;br /&gt;alert(c.nifty()); // Alerts "NIFTY!"&lt;/pre&gt;Within &lt;code&gt;#nifty&lt;/code&gt;, we refer to the function by name&amp;nbsp;&amp;mdash; no &lt;code&gt;this&lt;/code&gt;, that's very important!&amp;nbsp;&amp;mdash; which always refers to the right one. We get its &lt;code&gt;$super&lt;/code&gt; property, and use &lt;code&gt;Function#call&lt;/code&gt; on it. (We could use &lt;code&gt;Function#apply&lt;/code&gt; if we wanted.) We pass in &lt;code&gt;this&lt;/code&gt; as the context parameter so that &lt;code&gt;this&lt;/code&gt; is correct within the supercall.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Revisiting makeClass&lt;/h3&gt;&lt;br /&gt;I &lt;a href='http://groups.google.com/group/prototype-core/browse_thread/thread/db9ccdaae4f7f705'&gt;floated this supercalls idea&lt;/a&gt; on the Prototype Core development mailing list, and &lt;a href='http://www.allenmadsen.com/'&gt;Allen Madsen&lt;/a&gt; pointed out that if we're going to be using functions to create enclosing scope when defining classes, &lt;code&gt;makeClass&lt;/code&gt; should just support our passing those functions in directly rather than making us execute them first. It simplifies the syntax markedly:&lt;br /&gt;&lt;pre&gt;var Child = Helper.makeClass(Parent, function(){&lt;br /&gt;    function nifty() { &lt;br /&gt;        var rv = nifty.$super.call(this);&lt;br /&gt;        return rv.toUpperCase();&lt;br /&gt;    }&lt;br /&gt;    return {nifty: nifty};&lt;br /&gt;});&lt;br /&gt;var c = new Child();&lt;br /&gt;alert(c.nifty()); // Alerts "NIFTY!"&lt;/pre&gt;We just define the function rather than defining and calling it; &lt;code&gt;makeClass&lt;/code&gt; will call it for us. So let's go support that in &lt;code&gt;makeClass&lt;/code&gt; (we'll still support providing the specification object directly) by marking constructor functions (so we know whether we have a base class, since everything might be a function now&amp;nbsp;&amp;mdash; this was also Allen's idea) and then just invoking any functions we find to get their specification objects. (Code below under "Bringing It All Together".)&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Mixins&lt;/h3&gt;&lt;br /&gt;A fairly common pattern these days it to have "mixins" that can be mixed into classes. A "mixin" is a collection of functions that coordinate to provide some functionality, intended to be added to a class rather than to be a class in its own right. One mixin might be used by several different classes. Mixins are sometimes seen as a replacement for derivation, but to me they're an adjunct&amp;nbsp;&amp;mdash; there are times you derive, and other times you mix in.&lt;br /&gt;&lt;br /&gt;Mixins are the reason that &lt;code&gt;Helper.makeClass&lt;/code&gt; allows multiple specification objects. Suppose we have a mixin that provides semantics around getting and setting a "cool" property:&lt;br /&gt;&lt;pre&gt;var CoolMixin = (function(){&lt;br /&gt;    function setCool(cool) {&lt;br /&gt;        if (typeof cool != 'string') {&lt;br /&gt;            throw "Hey, man, that ain't cool.";&lt;br /&gt;        }&lt;br /&gt;        this.cool = cool;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    function getCool() {&lt;br /&gt;        return this.cool;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return {getCool: getCool, setCool: setCool};&lt;br /&gt;})();&lt;/pre&gt;Now we can mix that into any class:&lt;br /&gt;&lt;pre&gt;var CoolChild = Helper.makeClass(Parent, CoolMixin, function() {&lt;br /&gt;    function spiffy() {&lt;br /&gt;        // ...&lt;br /&gt;    }&lt;br /&gt;    return {spiffy: spiffy};&lt;br /&gt;});&lt;br /&gt;var cc = new CoolChild();&lt;br /&gt;alert(cc.nifty());  // Alerts "Nifty!" via Parent#nifty&lt;br /&gt;cc.setCool(1);      // throws the uncool exception&lt;/pre&gt;&lt;code&gt;CoolChild&lt;/code&gt; inherits from &lt;code&gt;Parent&lt;/code&gt;, but also gets the cool stuff from &lt;code&gt;CoolMixin&lt;/code&gt;. By convention (and in order to ensure that a subclass's own members take precedence), mixins are always included after the parent and before the child's own members.&lt;br /&gt;&lt;br /&gt;Mixins raise an issue for &lt;code&gt;makeClass&lt;/code&gt;: Normally, it modifies function instances, setting a &lt;code&gt;$super&lt;/code&gt; property on them if they override a base class function (it leaves them alone if they don't). But mixins are used in multiple classes, so we shouldn't touch them. While in practice it would be fairly harmless to set &lt;code&gt;$super&lt;/code&gt; on the mixin function if the mixin function didn't call &lt;code&gt;$super&lt;/code&gt; (which is definitely an edge case), it's still not right and in certain very edgy edge cases could cause class cross-talk, which is a Bad Thing(tm).&lt;br /&gt;&lt;br /&gt;To handle this, we can provide a means of marking methods as being mixin methods and telling &lt;code&gt;makeClass&lt;/code&gt; to leave them alone. (I actually mark the methods rather than doing it by context because some implementations&amp;nbsp;&amp;mdash; like Prototype&amp;nbsp;&amp;mdash; allow modifying hierarchies after initial derivation, in which case it's really important to know which functions are mixin functions and which aren't). It may seem to be pandering to an edge case, but there's effectively no runtime cost and the code is trivial, so let's do it&amp;nbsp;&amp;mdash; see &lt;code&gt;Helper.makeMixin&lt;/code&gt; below.&lt;br /&gt;&lt;br /&gt;Alternately, we can take a page from previous implementations and&amp;nbsp;&amp;mdash; in this one very specific case&amp;nbsp;&amp;mdash; wrap the mixin function so we can set the &lt;code&gt;$super&lt;/code&gt; property on the wrapper. I haven't done that here, but it's a viable solution if you think mixins calling &lt;code&gt;$super&lt;/code&gt; is a common enough use case for you.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Anonymouses Anonymous&lt;/h3&gt;&lt;br /&gt;Not everyone will want to use named functions; perhaps they have a large amount of legacy code using specification objects directly. Rather than leave them with the ugly syntax:&lt;br /&gt;&lt;pre&gt;arguments.callee.$super.call(this, ...);&lt;/pre&gt;...let's give them a helper method to take on some of that complexity:&lt;br /&gt;&lt;pre&gt;this.callSuper(arguments, ...);&lt;/pre&gt;But we don't want to do that all the time. Hey, that's the case for a mixin! See the &lt;code&gt;CallSuperMixin&lt;/code&gt; below.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Bringing It All Together&lt;/h3&gt;&lt;br /&gt;Okay, taking all of the above, mixing in an IE workaround (thank you, Prototype!), and adding in &lt;code&gt;Helper.makeMixin&lt;/code&gt;, we end up with &lt;a href='http://www.crowdersoftware.com/bimg/supercalls4.js'&gt;this&lt;/a&gt;:&lt;br /&gt;&lt;pre&gt;// Take IV: Explicitly handle mixins, provide a mixin for calling super when&lt;br /&gt;// working with anonymous functions.&lt;br /&gt;// Inspired by Prototype's Class class (http://prototypejs.org)&lt;br /&gt;// Copyright (C) 2009 by T.J. Crowder&lt;br /&gt;// Licensed under the Creative Commons Attribution License 2.0 (UK)&lt;br /&gt;// http://creativecommons.org/licenses/by/2.0/uk/&lt;br /&gt;var Helper = (function(){&lt;br /&gt;    var toStringProblematic,    // true if 'toString' may be missing from for..in&lt;br /&gt;        valueOfProblematic;     // true if 'valueOf' may be missing from for..in&lt;br /&gt;&lt;br /&gt;    // IE doesn't enumerate toString or valueOf; detect that (once) and&lt;br /&gt;    // remember so makeClass can deal with it. We do this with an anonymous&lt;br /&gt;    // function we don't keep a reference to to minimize what we keep&lt;br /&gt;    // around when we're done.&lt;br /&gt;    (function(){&lt;br /&gt;        var name;&lt;br /&gt;&lt;br /&gt;        toStringProblematic = valueOfProblematic = true;&lt;br /&gt;        for (name in {toString: true, valueOf: true}) {&lt;br /&gt;            if (name == 'toString') {&lt;br /&gt;                toStringProblematic = false;&lt;br /&gt;            }&lt;br /&gt;            if (name == 'valueOf') {&lt;br /&gt;                valueOfProblematic = false;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    })();&lt;br /&gt;&lt;br /&gt;    // Build and return a constructor; we do this with a separate function&lt;br /&gt;    // to minimize what the new constructor (a closure) closes over.&lt;br /&gt;    function makeConstructor() {&lt;br /&gt;&lt;br /&gt;        // Here's our basic constructor function (each class gets its own, a&lt;br /&gt;        // new one of these is created every time makeConstructor is called).&lt;br /&gt;        function ctor() {&lt;br /&gt;            // Call the initialize method&lt;br /&gt;            this.initialize.apply(this, arguments);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        return ctor;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // This function is used when a class doesn't have its own initialize&lt;br /&gt;    // function; since it does nothing and can only appear on base classes,&lt;br /&gt;    // all instances can share it.&lt;br /&gt;    function defaultInitialize() {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Get the names in a specification object, allowing for toString and&lt;br /&gt;    // valueOf issues&lt;br /&gt;    function getNames(members) {&lt;br /&gt;        var names,      // The names of the properties in 'members'&lt;br /&gt;            name,       // Each name&lt;br /&gt;            nameIndex;  // Index into 'names'&lt;br /&gt;&lt;br /&gt;        names = [];&lt;br /&gt;        nameIndex = 0;&lt;br /&gt;        for (name in members) {&lt;br /&gt;            names[nameIndex++] = name;&lt;br /&gt;        }&lt;br /&gt;        if (toStringProblematic &amp;&amp; typeof members.toString != 'undefined') {&lt;br /&gt;            names[nameIndex++] = 'toString';&lt;br /&gt;        }&lt;br /&gt;        if (valueOfProblematic &amp;&amp; typeof members.valueOf != 'undefined') {&lt;br /&gt;            names[nameIndex++] = 'valueOf';&lt;br /&gt;        }&lt;br /&gt;        return names;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // makeClass: Our public "make a class" function.&lt;br /&gt;    // Arguments:&lt;br /&gt;    // - base: An optional constructor for the base class.&lt;br /&gt;    // - ...:  One or more specification objects containing properties to&lt;br /&gt;    //         put on our class as members; or functions that return&lt;br /&gt;    //         specification objects. If a property is defined by more than one&lt;br /&gt;    //         specification object, the last in the list wins.&lt;br /&gt;    // Returns:&lt;br /&gt;    //     A constructor function for instances of the class.&lt;br /&gt;    //&lt;br /&gt;    // Typical use will be just one specification object, but allow for more&lt;br /&gt;    // in case the author is drawing members from multiple locations.&lt;br /&gt;    function makeClass() {&lt;br /&gt;        var base,       // Our base class (constructor function), if any&lt;br /&gt;            argsIndex,  // Index of first unused argument in 'arguments'&lt;br /&gt;            ctor,       // The constructor function we create and return&lt;br /&gt;            members,    // Each members specification object&lt;br /&gt;            names,      // The names of the properties in 'members'&lt;br /&gt;            nameIndex,  // Index into 'names'&lt;br /&gt;            name,       // Each name in 'names'&lt;br /&gt;            value,      // The value for each name&lt;br /&gt;            baseValue;  // The base class's value for the name&lt;br /&gt;&lt;br /&gt;        // We use this index to keep track of the arguments we've consumed&lt;br /&gt;        argsIndex = 0;&lt;br /&gt;&lt;br /&gt;        // Do we have a base?&lt;br /&gt;        if (typeof arguments[argsIndex] == 'function' &amp;&amp;&lt;br /&gt;            arguments[argsIndex]._isConstructor) {&lt;br /&gt;            // Yes&lt;br /&gt;            base = arguments[argsIndex++];&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Get our constructor&lt;br /&gt;        ctor = makeConstructor();&lt;br /&gt;        ctor._isConstructor = true;&lt;br /&gt;&lt;br /&gt;        // Apply the base class if any by assigning an instance of it to&lt;br /&gt;        // our constructor's prototype&lt;br /&gt;        if (base) {&lt;br /&gt;            ctor.prototype = new base();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Set our constructor property so "this.constructor" resolves&lt;br /&gt;        // correctly&lt;br /&gt;        ctor.prototype.constructor = ctor;&lt;br /&gt;&lt;br /&gt;        // Assign the members from the specification object(s) to the prototype&lt;br /&gt;        // Again, typically there's only spec object, but allow for more&lt;br /&gt;        while (argsIndex &lt; arguments.length) {&lt;br /&gt;            // Get this specification object&lt;br /&gt;            members = arguments[argsIndex++];&lt;br /&gt;            if (typeof members == 'function') {&lt;br /&gt;                members = members();&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            // Get all of its names&lt;br /&gt;            names = getNames(members);&lt;br /&gt;&lt;br /&gt;            // Copy the members&lt;br /&gt;            for (nameIndex = names.length - 1; nameIndex &gt;= 0; --nameIndex) {&lt;br /&gt;                name = names[nameIndex];&lt;br /&gt;                value = members[name];&lt;br /&gt;                if (base &amp;&amp; typeof value == 'function' &amp;&amp; !value._isMixinFunction) {&lt;br /&gt;                    baseValue = base.prototype[name];&lt;br /&gt;                    if (typeof baseValue == 'function') {&lt;br /&gt;                        value.$super = baseValue;&lt;br /&gt;                    }&lt;br /&gt;                }&lt;br /&gt;                ctor.prototype[name] = value;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // If there's no initialize function, provide one&lt;br /&gt;        if (!('initialize' in ctor.prototype)) {&lt;br /&gt;            // Note that this can only happen in base classes; in a derived&lt;br /&gt;            // class, the check above will find the base class's version if the&lt;br /&gt;            // subclass didn't define one.&lt;br /&gt;            ctor.prototype.initialize = defaultInitialize;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Return the constructor&lt;br /&gt;        return ctor;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // makeMixin: Our public "make a mixin" function.&lt;br /&gt;    // Arguments:&lt;br /&gt;    // - ...:  One or more specification objects containing properties to&lt;br /&gt;    //         put on our class as members; or functions that return&lt;br /&gt;    //         specification objects. If a property is defined by more than one&lt;br /&gt;    //         specification object, the last in the list wins.&lt;br /&gt;    // Returns:&lt;br /&gt;    //     A specification object containing all of the members, flagged as&lt;br /&gt;    //     mixin members.&lt;br /&gt;    function makeMixin() {&lt;br /&gt;        var rv,         // Our return value&lt;br /&gt;            argsIndex,  // Index of first unused argument in 'arguments'&lt;br /&gt;            members,    // Each members specification object&lt;br /&gt;            names,      // The names in each 'members'&lt;br /&gt;            value;      // Each value as we copy it&lt;br /&gt;&lt;br /&gt;        // Set up our return object&lt;br /&gt;        rv = {};&lt;br /&gt;&lt;br /&gt;        // Loop through the args (usually just one, but...)&lt;br /&gt;        argsIndex = 0;&lt;br /&gt;        while (argsIndex &lt; arguments.length) {&lt;br /&gt;            // Get this members specification object&lt;br /&gt;            members = arguments[argsIndex++];&lt;br /&gt;            if (typeof members == 'function') {&lt;br /&gt;                members = members();&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            // Get its names&lt;br /&gt;            names = getNames(members);&lt;br /&gt;&lt;br /&gt;            // Copy its members, marking them as we go&lt;br /&gt;            for (nameIndex = names.length - 1; nameIndex &gt;= 0; --nameIndex) {&lt;br /&gt;                name = names[nameIndex];&lt;br /&gt;                value = members[name];&lt;br /&gt;                if (typeof value == 'function') {&lt;br /&gt;                    value._isMixinFunction = true;&lt;br /&gt;                }&lt;br /&gt;                rv[name] = value;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Return the consolidated, marked specification object&lt;br /&gt;        return rv;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // Return our public members&lt;br /&gt;    return {&lt;br /&gt;        makeClass: makeClass,&lt;br /&gt;        makeMixin: makeMixin&lt;br /&gt;        };&lt;br /&gt;})();&lt;/pre&gt;Which lets us do things like this:&lt;br /&gt;&lt;pre&gt;var Parent = Helper.makeClass(function(){&lt;br /&gt;    function hierarchy() {&lt;br /&gt;        return "P";&lt;br /&gt;    }&lt;br /&gt;    return {hierarchy: hierarchy};&lt;br /&gt;});&lt;br /&gt;var Child = Helper.makeClass(Parent, function(){&lt;br /&gt;    function hierarchy() {&lt;br /&gt;        return hierarchy.$super.call(this) + " &lt; C";&lt;br /&gt;    }&lt;br /&gt;    return {hierarchy: hierarchy};&lt;br /&gt;});&lt;br /&gt;var GrandChild = Helper.makeClass(Child, function(){&lt;br /&gt;    function hierarchy() {&lt;br /&gt;        return hierarchy.$super.call(this) + " &lt; GC";&lt;br /&gt;    }&lt;br /&gt;    return {hierarchy: hierarchy};&lt;br /&gt;});&lt;br /&gt;var gc = new GrandChild();&lt;br /&gt;alert(gc.hierarchy()); // Alerts "P &lt; C &lt; GC"&lt;/pre&gt;And I believe I promised a sample mixin to help those anonymouses:&lt;br /&gt;&lt;pre&gt;// Define our CallSuper mixin&lt;br /&gt;Helper.CallSuperMixin = makeMixin(function() {&lt;br /&gt;    function callSuper(ref) {&lt;br /&gt;        var f,          // The function to call&lt;br /&gt;            args,       // Arguments to pass it, if we have any&lt;br /&gt;            len,        // Length of args to pass&lt;br /&gt;            srcIndex,   // When copying, the index into 'arguments'&lt;br /&gt;            destIndex,  // When copying args, the index into 'args'&lt;br /&gt;            rv;         // Our return value&lt;br /&gt;&lt;br /&gt;        // Get the function to call: If they pass in a function, it's the&lt;br /&gt;        // subclass's version so look on $super; otherwise, they've passed&lt;br /&gt;        // in 'arguments' and it's on arguments.callee.$super.&lt;br /&gt;        f = typeof ref == 'function' ? ref.$super : ref.callee.$super;&lt;br /&gt;&lt;br /&gt;        // Only proceed if we have 'f'&lt;br /&gt;        if (f) {&lt;br /&gt;            // If there are no args to pass on, use Function#call&lt;br /&gt;            if (arguments.length == 1) {&lt;br /&gt;                rv = f.call(this);&lt;br /&gt;            } else {&lt;br /&gt;                // We have args to pass on, build them up.&lt;br /&gt;                // Note that doing this ourselves is more efficient on most&lt;br /&gt;                // implementations than applying Array.prototype.slice to&lt;br /&gt;                // 'arguments', even though it's built in; the call to it&lt;br /&gt;                // is expensive (dramatically, on some platforms).&lt;br /&gt;                len = arguments.length - 1;&lt;br /&gt;                args = new Array(len);&lt;br /&gt;                srcIndex = 1;&lt;br /&gt;                destIndex = 0;&lt;br /&gt;                while (destIndex &lt; len) {&lt;br /&gt;                    args[destIndex++] = arguments[srcIndex++];&lt;br /&gt;                }&lt;br /&gt;&lt;br /&gt;                // Use Function#apply&lt;br /&gt;                rv = f.apply(this, args);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // Done&lt;br /&gt;        return rv;    // Will be undefined if there was no 'f' to call&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return {callSuper: callSuper};&lt;br /&gt;});&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Conclusion&lt;/h3&gt;&lt;br /&gt;The goal of this post is not for people to run off and start using the &lt;code&gt;Helper&lt;/code&gt; provided here. The goal is to demonstrate a really simple, highly efficient means of implementing supercalls in these sorts of libraries, and discussing some edge cases around doing so. If you use Prototype, you might want to take a look at my &lt;a href='http://github.com/tjcrowder/prototype/commit/79d3e1dfd32220299f0a5aceacfc6fd3ffa2a089'&gt;patch for Prototype 1.6.1&lt;/a&gt; (I have no idea whether that will make it into Prototype), which handles dynamic redefinition and such (although that patch doesn't&amp;nbsp;&amp;mdash; yet&amp;nbsp;&amp;mdash; handle mixins).&lt;br /&gt;&lt;br /&gt;We've talked about a lot of things, so let's remind oursselves of what the mechanism is at its roots:&lt;ul&gt;&lt;li&gt;Have a "make a class" function.&lt;/li&gt;&lt;li&gt;In that function, detect that a subclass function (&lt;code&gt;Child#nifty&lt;/code&gt;) is overriding a superclass function (&lt;code&gt;Parent#nifty&lt;/code&gt;) and, if so, put a reference to the superclass function on the subclass function instance as a property.&lt;/li&gt;&lt;li&gt;To call a superclass function from a subclass function, authors use &lt;code&gt;Function#call&lt;/code&gt; or &lt;code&gt;Function#apply&lt;/code&gt; on the &lt;code&gt;$super&lt;/code&gt; property of the subclass function instance (being sure to get the function directly, &lt;em&gt;not&lt;/em&gt; via &lt;code&gt;this&lt;/code&gt;). This is simplest and fastest with named functions, but possible with anonymous ones too.&lt;/li&gt;&lt;li&gt;Allow for mixins, if you're into that sort of thing (and why not, they're cool)&lt;br&gt;Oh, and of course:&lt;/li&gt;&lt;li&gt;Profit!&lt;/li&gt;&lt;/ul&gt;Many thanks again to JDD, kangax, Allen, and others who've helped me hammer this out!&lt;br /&gt;&lt;br /&gt;Happy Coding,&lt;br /&gt;&lt;br /&gt;--&amp;nbsp;T.J.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-4742726851690218350?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/X9RWxdhSMLA" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/X9RWxdhSMLA/simple-efficient-supercalls-in.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2009/09/simple-efficient-supercalls-in.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-876026099464689467</guid><pubDate>Fri, 14 Nov 2008 10:22:00 +0000</pubDate><atom:updated>2008-11-14T10:29:15.977Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">OT</category><title>COMPLETELY off-topic...</title><description>...but if this doesn't gob-smack you, you're dead inside:&lt;br /&gt;&lt;a href="http://news.bbc.co.uk/1/hi/sci/tech/7725584.stm"&gt;http://news.bbc.co.uk/1/hi/sci/tech/7725584.stm&lt;/a&gt;&lt;br /&gt;I mean, we've known they were there, in theory, at least since Newton; we've known they were there, by observation (star wobbles, etc.), for 20 years.  But this is direct observation.  We can &lt;span style="font-style: italic;"&gt;see&lt;/span&gt; them.  To me, this is a Neil Armstrong moment.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-876026099464689467?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/4XU87BgK0ZI" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/4XU87BgK0ZI/completely-off-topic.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/11/completely-off-topic.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-5734543818132776064</guid><pubDate>Sun, 19 Oct 2008 12:00:00 +0000</pubDate><atom:updated>2008-10-19T13:01:50.121+01:00</atom:updated><title>Unobtrusiveness</title><description>Another link-post today (although again a link to a snippet I've written, so not completey OT) since most of my writing time is going to the Unofficial Prototype &amp; script.aculo.us wiki at the moment: &lt;a href="http://proto-scripty.wikidot.com/prototype:how-to-using-unobtrusive-javascript"&gt;How To - Using Unobtrusive JavaScript&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-5734543818132776064?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/b6RWdNH2xOg" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/b6RWdNH2xOg/unobtrusiveness.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/10/unobtrusiveness.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-5830750848748221014</guid><pubDate>Thu, 16 Oct 2008 14:52:00 +0000</pubDate><atom:updated>2008-10-16T15:57:19.135+01:00</atom:updated><title>Minimizing Download Times</title><description>Hello all,&lt;br /&gt;&lt;br /&gt;That's right, first post since...wow, since April.  And it's not even a post, it's sort of a link-post.&lt;br /&gt;&lt;br /&gt;I've been doing some work helping build the Prototype user community (moderating the &lt;a href="http://groups.google.com/group/prototype-scriptaculous"&gt;user discussion group&lt;/a&gt;, creating an &lt;a href="http://proto-scripty.wikidot.com"&gt;unofficial wiki&lt;/a&gt;, that kind of thing) and as part of that I've been doing little mini-articles, much like the ones I expected to do here.&lt;br /&gt;&lt;br /&gt;So if you're writing web applications or web pages and you're interested in minimizing the download times for your scripts, check out this article I posted over there:  &lt;a href="http://proto-scripty.wikidot.com/prototype:tip-minimizing-download-times"&gt;Tip&amp;nbsp;-&amp;nbsp;Minimizing Download Times&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-5830750848748221014?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/GAjIQUAznus" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/GAjIQUAznus/minimizing-download-times.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/10/minimizing-download-times.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-2678400766479808536</guid><pubDate>Tue, 01 Apr 2008 16:30:00 +0000</pubDate><atom:updated>2008-04-03T11:38:31.713+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">JavaScript</category><category domain="http://www.blogger.com/atom/ns#">pitfall</category><category domain="http://www.blogger.com/atom/ns#">this</category><title>You must remember 'this'</title><description>&lt;span style="font-style:italic;"&gt;Of all the tech blogs in all the sites in all the worldwide web, you walk into mine...&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;If you hang out in JavaScript-oriented newsgroups &lt;a href="http://groups.google.com/group/comp.lang.javascript/topics"&gt;like&lt;/a&gt; &lt;a href="http://groups.google.com/group/rubyonrails-spinoffs/topics"&gt;these&lt;/a&gt; for any length of time, you will eventually see some variation of this question:&lt;blockquote&gt;&lt;span style="font-style:italic;"&gt;Hey, why doesn't this work?&lt;/span&gt;&lt;pre&gt;function MyWidget(name)&lt;br /&gt;{&lt;br /&gt;    this.name = name;&lt;br /&gt;    this.element = null;&lt;br /&gt;}&lt;br /&gt;MyWidget.prototype.showName = function()&lt;br /&gt;{&lt;br /&gt;    alert('The name is ' + this.name);&lt;br /&gt;}&lt;br /&gt;MyWidget.prototype.hookElement = function(element)&lt;br /&gt;{&lt;br /&gt;    this.element = element;&lt;br /&gt;    Event.observe(this.element, 'click', this.showName);&lt;br /&gt;}&lt;br /&gt;function test()&lt;br /&gt;{&lt;br /&gt;    var widget;&lt;br /&gt;&lt;br /&gt;    widget = new MyWidget('Test Name');&lt;br /&gt;    widget.hookElement(document.getElementById('testDiv'));&lt;br /&gt;}&lt;/pre&gt;&lt;span style="font-style:italic;"&gt;"testDiv" is a div in the document, and I know that I'm not calling the test() function before the DOM is loaded, so why is it when I click the div I get the message "The name is undefined"?!&lt;/span&gt;&lt;/blockquote&gt;(As always, I'm using some &lt;a href="http://blog.niftysnippets.org/2008/03/convenience-syntax-in-examples.html"&gt;convenience syntax&lt;/a&gt; in the above for hooking up the event handler.)&lt;br /&gt;&lt;br /&gt;The OP (original poster) might even follow on with:&lt;blockquote&gt;&lt;span style="font-style:italic;"&gt;I even tried changing the observe() line to this:&lt;pre&gt;Event.observe(this.element, 'click', function() {&lt;br /&gt;    this.showName();&lt;br /&gt;});&lt;/pre&gt;because I heard somewhere that you have to do that, but that's even worse, it causes an error saying this.showName() isn't a function?!&lt;/span&gt;&lt;/blockquote&gt;The issue here is that the OP hasn't quite grokked "this" and its special role in the JavaScript world.&lt;br /&gt;&lt;br /&gt;I talked a bit about 'this' over &lt;a href="http://blog.niftysnippets.org/2008/03/mythical-methods.html"&gt;here&lt;/a&gt;, but I wanted to do a post focussing on the specific pitfall the OP above, like so many of us, has fallen into (forgetting 'this') and how you deal with it.&lt;br /&gt;&lt;br /&gt;Let's look at what's wrong with this line first:&lt;pre&gt;Event.observe(this.element, 'click', this.showName); // Wrong&lt;/pre&gt;JavaScript doesn't have methods (see link above), and so &lt;code&gt;&lt;span style="font-weight:bold;"&gt;this.showName&lt;/span&gt;&lt;/code&gt; just returns a function reference with absolutely no connection to the instance the OP wanted to bind to the element.  It's just a function.  (Used properly, this is a powerful feature, but in this situation it's causing the OP some trouble.)  Recall that &lt;code&gt;&lt;span style="font-weight:bold;"&gt;showName&lt;/span&gt;&lt;/code&gt; is defined like this:&lt;pre&gt;MyWidget.prototype.showName = function()&lt;br /&gt;{&lt;br /&gt;    alert('The name is ' + this.name);&lt;br /&gt;}&lt;/pre&gt;Within the code, 'this' is determined not by where the event handler is set up, but by how the function gets called.  Most likely, 'this' will be a reference to the element that was clicked ('testDiv'), because modern browsers use the element related to the event as 'this' within event handlers.  Consequently, &lt;code&gt;&lt;span style="font-weight:bold;"&gt;this.name&lt;/span&gt;&lt;/code&gt; is undefined unless the element in question happens to have a &lt;code&gt;&lt;span style="font-weight:bold;"&gt;name&lt;/span&gt;&lt;/code&gt; attribute.&lt;br /&gt;&lt;br /&gt;So to get the intended effect, you have to wrap the call to &lt;code&gt;&lt;span style="font-weight:bold;"&gt;this.showName()&lt;/span&gt;&lt;/code&gt; so that 'this' is the MyWidget instance when the code gets executed&amp;nbsp;-- you must remember 'this'.  Which is probably what the OP heard about when he tried this:&lt;pre&gt;Event.observe(this.element, 'click', function() {&lt;br /&gt;    this.showName();&lt;br /&gt;}); // Still wrong&lt;/pre&gt;This is getting closer, and in fact it would work if we were using a variable to reference the widget rather than 'this', but because it's 'this', we actually still have exactly the same problem we had before: When the event handler gets called, 'this' is the element, not the widget, and so there's no &lt;code&gt;&lt;span style="font-weight:bold;"&gt;showName()&lt;/span&gt;&lt;/code&gt; function to call.&lt;br /&gt;&lt;br /&gt;So how do we deal with this?  Well, here's one approach I've seen to rewriting the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;hookElement&lt;/span&gt;&lt;/code&gt; function:&lt;pre&gt;MyWidget.prototype.hookElement = function(element)&lt;br /&gt;{&lt;br /&gt;    var self;&lt;br /&gt;&lt;br /&gt;    this.element = element;&lt;br /&gt;    self = this;&lt;br /&gt;    Event.observe(this.element, 'click', function() {&lt;br /&gt;        self.showName();&lt;br /&gt;    });&lt;br /&gt;}&lt;/pre&gt;This works because we're no longer using 'this' within the event handler, we're using 'self' (the event handler has access to 'self' because it's a closure; more &lt;a href="http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html"&gt;here&lt;/a&gt;). So that solution works.  I can't say I like it, though.  It just feels...hacky, I guess.  But still, it works, and although it looks a bit funny the first time, if you're familiar with the idiom you read right past it thereafter.  You just need to be sure the closure isn't unnecessarily preserving some other big amount of data from elsewhere in the function.&lt;br /&gt;&lt;br /&gt;Personally, though, I prefer using a reusable "binding" function.  Many JavaScript toolkits have these (such as Prototype's &lt;a href="http://www.prototypejs.org/api/function/bind"&gt;bind()&lt;/a&gt; and &lt;a href="http://www.prototypejs.org/api/function/bindAsEventListener"&gt;bindAsEventListener()&lt;/a&gt;), but it's not complicated:&lt;pre&gt;function bind(f, obj)&lt;br /&gt;{&lt;br /&gt;    return function() {&lt;br /&gt;        return f.apply(obj, arguments);&lt;br /&gt;    };&lt;br /&gt;}&lt;/pre&gt;This is a function factory: It creates functions that, when called, will call the given function with the given object set as 'this' (using JavaScript's convenient &lt;code&gt;&lt;span style="font-weight:bold;"&gt;apply()&lt;/span&gt;&lt;/code&gt; function; insert your own "&lt;span style="font-style:italic;"&gt;The fundamental things apply&lt;/span&gt;" joke here). Now we can rewrite the OP's &lt;code&gt;&lt;span style="font-weight:bold;"&gt;hookElement&lt;/span&gt;&lt;/code&gt; function like so (changes from the original at the top in bold):&lt;pre&gt;MyWidget.prototype.hookElement = function(element)&lt;br /&gt;{&lt;br /&gt;    this.element = element;&lt;br /&gt;    Event.observe(this.element, 'click',&lt;br /&gt;        &lt;span style="font-weight:bold;"&gt;bind(&lt;/span&gt;this.showName&lt;span style="font-weight:bold;"&gt;, this)&lt;/span&gt;&lt;br /&gt;    );&lt;br /&gt;}&lt;/pre&gt;You might be wondering why we have to specify 'this' twice. Remember that &lt;code&gt;&lt;span style="font-weight:bold;"&gt;this.showName&lt;/span&gt;&lt;/code&gt; just returns a function reference, with nothing about the instance (we could replace &lt;code&gt;&lt;span style="font-weight:bold;"&gt;this.showName&lt;/span&gt;&lt;/code&gt; in the above with &lt;code&gt;&lt;span style="font-weight:bold;"&gt;MyWidget.prototype.showName&lt;/span&gt;&lt;/code&gt; if we liked).  If we want &lt;code&gt;&lt;span style="font-weight:bold;"&gt;bind()&lt;/span&gt;&lt;/code&gt; to know what instance we want to bind the function to, we have to specify it&amp;nbsp;-- the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;this&lt;/span&gt;&lt;/code&gt; at the end.&lt;br /&gt;&lt;br /&gt;And that's it!  Now the event handler works as the OP expected it to.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-2678400766479808536?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/07_39xCsXR4" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/07_39xCsXR4/you-must-remember-this.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/04/you-must-remember-this.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-2655690554511749465</guid><pubDate>Sat, 29 Mar 2008 12:59:00 +0000</pubDate><atom:updated>2008-03-29T13:13:59.305Z</atom:updated><title>What's in a name?</title><description>Micro-post today, folks:&lt;br /&gt;&lt;br /&gt;You see a fair bit of confusion from newbies in mailing lists around the "name" attribute vs. the "id" attribute. For instance, I recently saw a "how do I do this" -style post asking how to deal with a form, with the sample being:&lt;pre&gt;&amp;lt;form name='form1'&amp;gt;&lt;br /&gt;&amp;lt;input type='checkbox' id='cb1'&amp;gt;Checkbox 1&lt;br /&gt;&amp;lt;/form&amp;gt;&lt;/pre&gt;The poster wanted to know how to retrieve the form and submit it (along with some further information) via Prototype's &lt;a href="http://www.prototypejs.org/api/ajax/updater"&gt;&lt;code&gt;&lt;span style="font-weight:bold;"&gt;Ajax.Updater&lt;/span&gt;&lt;/code&gt;&lt;/a&gt;. So he wanted to use the &lt;a href="http://www.prototypejs.org/api/form/serialize"&gt;&lt;code&gt;&lt;span style="font-weight:bold;"&gt;serialize()&lt;/span&gt;&lt;/code&gt;&lt;/a&gt; method Prototype adds to form elements when it extends them (e.g., when you retrieve the element using &lt;a href="http://www.prototypejs.org/api/utility/dollar"&gt;&lt;code&gt;&lt;span style="font-weight:bold;"&gt;$()&lt;/span&gt;&lt;/code&gt;&lt;/a&gt;).&lt;br /&gt;&lt;br /&gt;Consequently, the use of "id" and "name" attributes in his example was exactly backward: He wanted to be able to retrieve the form using &lt;code&gt;&lt;span style="font-weight:bold;"&gt;$()&lt;/span&gt;&lt;/code&gt;, which is a general-purpose routine that retrieves elements by their unique ID, and then have the form fields submitted&amp;nbsp;-- but the form field had no name.&lt;br /&gt;&lt;br /&gt;Here's the mantra:&lt;blockquote&gt;&lt;span style="font-style:italic;"&gt;Elements have &lt;span style="font-weight:bold;"&gt;IDs&lt;/span&gt;; form fields have &lt;span style="font-weight:bold;"&gt;names&lt;/span&gt;.&lt;/span&gt;&lt;/blockquote&gt;IDs are unique in the document; form field names are not (necessarily).&lt;br /&gt;&lt;br /&gt;Two further notes:&lt;br /&gt;&lt;br /&gt;1. Form fields can &lt;span style="font-style:italic;"&gt;also&lt;/span&gt; have IDs if you need to refer to their elements in your code (to enable/disable them, etc.), but in terms of sending in a form, fields have names.&lt;br /&gt;&lt;br /&gt;2. You don't have to use an ID to get at the element for a form; you can use a name and then get at the form element via &lt;code&gt;&lt;span style="font-weight:bold;"&gt;document.YourFormName&lt;/span&gt;&lt;/code&gt; in your JavaScript code.  But nowadays we mostly look elements up by their unique IDs; and in the specific case of the question from the poster above, since he was going to want to use &lt;code&gt;&lt;span style="font-weight:bold;"&gt;$()&lt;/span&gt;&lt;/code&gt;, he would want an ID.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-2655690554511749465?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/ZF3HduxN26s" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/ZF3HduxN26s/whats-in-name.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/03/whats-in-name.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-3456807625915222681</guid><pubDate>Mon, 24 Mar 2008 22:00:00 +0000</pubDate><atom:updated>2008-03-25T14:34:27.693Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">JavaScript</category><category domain="http://www.blogger.com/atom/ns#">method</category><category domain="http://www.blogger.com/atom/ns#">this</category><title>Mythical methods</title><description>We frequently talk about JavaScript objects having &lt;span style="font-style:italic;"&gt;methods&lt;/span&gt;. This is just a convenient myth. JavaScript has functions, but it doesn't have &lt;span style="font-style:italic;"&gt;methods&lt;/span&gt;.  It doesn't need them.  Its functions, combined with some syntactic sugar, are more than up to the job.&lt;br /&gt;&lt;br /&gt;What is a "method"?  I'd have to say that the &lt;a href="http://en.wikipedia.org/wiki/Method_%28computer_science%29"&gt;definition&lt;/a&gt; given on Wikipedia is pretty good. As of this writing, it says a method is&lt;blockquote&gt;&lt;span style="font-style:italic;"&gt;...a subroutine that is exclusively associated either with a class...or with an object...&lt;/span&gt;&lt;/blockquote&gt;Yeah, JavaScript doesn't have any of those.  Granted it &lt;span style="font-style:italic;"&gt;seems&lt;/span&gt; to have them.  For example:&lt;pre&gt;function Guess(killer, location, weapon)&lt;br /&gt;{&lt;br /&gt;    this.killer = killer;&lt;br /&gt;    this.location = location;&lt;br /&gt;    this.weapon = weapon;&lt;br /&gt;}&lt;br /&gt;Guess.prototype.accuse = function()&lt;br /&gt;{&lt;br /&gt;    alert('It was ' + this.killer&lt;br /&gt;        + ' in the ' + this.location&lt;br /&gt;        + ' with the ' + this.weapon&lt;br /&gt;        + '!');&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;function testGuess()&lt;br /&gt;{&lt;br /&gt;    var mustardStudyLeadPipe;&lt;br /&gt;    var plumHallRope;&lt;br /&gt;&lt;br /&gt;    mustardStudyLeadPipe = new Guess(&lt;br /&gt;        'Colonel Mustard',&lt;br /&gt;        'study',&lt;br /&gt;        'lead pipe');&lt;br /&gt;    mustardStudyLeadPipe.accuse();&lt;br /&gt;&lt;br /&gt;    plumHallRope = new Guess(&lt;br /&gt;        'Professor Plum',&lt;br /&gt;        'hall',&lt;br /&gt;        'rope');&lt;br /&gt;    plumHallRope.accuse();&lt;br /&gt;}&lt;/pre&gt;Running &lt;code&gt;&lt;span style="font-weight:bold;"&gt;testGuess&lt;/span&gt;&lt;/code&gt; does indeed show us&lt;blockquote&gt;"It was Colonel Mustard in study with the lead pipe!"&lt;/blockquote&gt;and then&lt;blockquote&gt;"It was Professor Plum in hall with the rope!"&lt;/blockquote&gt;so that looks an awful lot like &lt;code&gt;&lt;span style="font-weight:bold;"&gt;accuse&lt;/span&gt;&lt;/code&gt; is a method of &lt;code&gt;&lt;span style="font-weight:bold;"&gt;Guess&lt;/span&gt;&lt;/code&gt; objects.&lt;br /&gt;&lt;br /&gt;Except it isn't.  Let's add a bit to our &lt;code&gt;&lt;span style="font-weight:bold;"&gt;testGuess&lt;/span&gt;&lt;/code&gt; function (new bits in bold):&lt;pre&gt;function testGuess()&lt;br /&gt;{&lt;br /&gt;    var mustardStudyLeadPipe;&lt;br /&gt;    var plumHallRope;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;    var accuse;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;    mustardStudyLeadPipe = new Guess(&lt;br /&gt;        'Colonel Mustard',&lt;br /&gt;        'study',&lt;br /&gt;        'lead pipe');&lt;br /&gt;    mustardStudyLeadPipe.accuse();&lt;br /&gt;&lt;br /&gt;    plumHallRope = new Guess(&lt;br /&gt;        'Professor Plum',&lt;br /&gt;        'hall',&lt;br /&gt;        'rope');&lt;br /&gt;    plumHallRope.accuse();&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;    accuse = mustardStudyLeadPipe.accuse;&lt;br /&gt;    accuse();&lt;/span&gt;&lt;br /&gt;}&lt;/pre&gt;What does the final call to &lt;code&gt;&lt;span style="font-weight:bold;"&gt;accuse&lt;/span&gt;&lt;/code&gt; show?  Does it accuse Colonel Mustard?  No, all we've done is get a reference to the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;accuse&lt;/span&gt;&lt;/code&gt; &lt;span style="font-style:italic;"&gt;function&lt;/span&gt; into our local variable, there's nothing there (or in the function definition) that refers to the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;mustardStudyLeadPipe&lt;/span&gt;&lt;/code&gt; instance or indeed anything related to &lt;code&gt;&lt;span style="font-weight:bold;"&gt;Guess&lt;/span&gt;&lt;/code&gt;. No, what this shows will depend on the HTML document in which it's found, but it'll be something along these lines:&lt;blockquote&gt;"It was undefined in the http://blog.niftysnippets.org with the undefined!"&lt;/blockquote&gt;Why? Because we didn't do anything to define "this" within the function. (I'll come back to details on why we'd get seemingly-odd alert that includes a URL in a bit.)&lt;br /&gt;&lt;br /&gt;There are three main things about JavaScript that make it seem to have methods (leaving aside prototypes and "classes" for the moment):  The "this" keyword, the fact that object properties can refer to functions (since they are, after all, just objects), and the fact that when you execute a function using "dotted" notation (e.g., &lt;code&gt;&lt;span style="font-weight:bold;"&gt;object.function()&lt;/span&gt;&lt;/code&gt;), the object is set automatically as "this" within the function call.&lt;br /&gt;&lt;br /&gt;Let's look at each of those.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;The "this" keyword:&lt;/span&gt; This keyword looks familiar if you're coming to JavaScript from a background in C++, Java, C#, and the like, where "this" within a method is guaranteed to refer to an instance of the class defining the method (or a subclass). And in JavaScript, "this" does refer to an object instance, but that's where the similarity ends.  Other than the name being the same and it referencing an object, it bears no relation to the "this" keyword in class-based languages like C++, Java, or C#.  In fact, in many ways, "this" is actually just a function argument that is supplied in a non-obvious (but convenient!) way.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Functions as properties:&lt;/span&gt; Let's look again at one line from the code above:&lt;pre&gt;mustardStudyLeadPipe.accuse();&lt;/pre&gt;If we were talking about that line of code, we'd probably say "...the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;accuse&lt;/span&gt;&lt;/code&gt; method of the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;mustardStudyLeadPipe&lt;/span&gt;&lt;/code&gt; object...", which is a useful and convenient way to put it.  A more painstakingly-geeky-accurate way of putting it, though, would be "...the function referenced by the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;accuse&lt;/span&gt;&lt;/code&gt; property of the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;mustardStudyLeadPipe&lt;/span&gt;&lt;/code&gt; object..."  Not that anyone's going to say that, but that's really what's going on.  Objects don't have methods, they have properties; it's just that a property can refer to a function, since functions are objects like everything else.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Functions called using dotted notation get "this" set for them:&lt;/span&gt; This is the part that really makes it seem like JavaScript has methods:  The "this" reference gets set automagically to the object instance if you call a method using dotted notation.  Let's look at that call again:&lt;pre&gt;mustardStudyLeadPipe.accuse();&lt;/pre&gt;This does three &lt;span style="font-style:italic;"&gt;completely distinct&lt;/span&gt; things: Firstly, it identifies a function to call by getting the function reference from an object property; secondly, it says to execute the function and return its result rather than just get a reference to it (the parentheses do that); and thirdly, it says that within that call, use the object in question as "this". These completely distinct things are combined in that notation for our convenience.  Getting the function reference from an object property doesn't link it in any way to the object the property came from (as our &lt;code&gt;&lt;span style="font-weight:bold;"&gt;accuse&lt;/span&gt;&lt;/code&gt; test above confirmed), it just gets a reference the function; the JavaScript engine treats dotted notation calls as special and sets up "this" accordingly, but it has nothing to do with the function being called.&lt;br /&gt;&lt;br /&gt;Lets prove that another way:&lt;pre&gt;function testGuess2()&lt;br /&gt;{&lt;br /&gt;    var plumHallRope;&lt;br /&gt;    var fakeGuess;&lt;br /&gt;&lt;br /&gt;    plumHallRope = new Guess(&lt;br /&gt;        'Professor Plum',&lt;br /&gt;        'hall',&lt;br /&gt;        'rope');&lt;br /&gt;    plumHallRope.accuse();&lt;br /&gt;&lt;br /&gt;    fakeGuess = {};&lt;br /&gt;    fakeGuess.location = 'library';&lt;br /&gt;    fakeGuess.killer = 'Mrs. Peacock';&lt;br /&gt;    fakeGuess.weapon = 'revolver';&lt;br /&gt;    fakeGuess.demo = plumHallRope.accuse;&lt;br /&gt;    fakeGuess.demo();&lt;br /&gt;}&lt;/pre&gt;This accuses Professor Plum as before, and then:&lt;blockquote&gt;"It was Mrs. Peacock in the library with the revolver!"&lt;/blockquote&gt;The exact same function produces the alerts in both cases, it's purely the way it was called that defined "this". The &lt;code&gt;&lt;span style="font-weight:bold;"&gt;fakeGuess&lt;/span&gt;&lt;/code&gt; object isn't even really a &lt;code&gt;&lt;span style="font-weight:bold;"&gt;Guess&lt;/span&gt;&lt;/code&gt;&amp;nbsp;-- "&lt;code&gt;&lt;span style="font-weight:bold;"&gt;fakeGuess instanceof Guess&lt;/span&gt;&lt;/code&gt;" returns false&amp;nbsp;-- but it has all of the properties the function expects (killer, location, weapon), and so it works just fine (this is something we'll come back to in a later post).  Essentially, "this" is just a function argument that's passed into the function as an implicit feature of the dotted notation.&lt;br /&gt;&lt;br /&gt;We can also do it explicitly.  JavaScript gives us the &lt;span style="font-weight:bold;"&gt;call&lt;/span&gt; and &lt;span style="font-weight:bold;"&gt;apply&lt;/span&gt; methods on function instances, with which we can say explicitly what we want "this" to be. (They do the same thing, they just provide different ways to specify the function's arguments.)  If you say &lt;span style="font-weight:bold;"&gt;&lt;span style="font-style:italic;"&gt;myfunction&lt;/span&gt;.call(&lt;span style="font-style:italic;"&gt;myobject&lt;/span&gt;)&lt;/span&gt;, you're saying "call &lt;span style="font-style:italic;"&gt;myfunction&lt;/span&gt; and use &lt;span style="font-style:italic;"&gt;myobject&lt;/span&gt; as 'this'", which is what the dotted notation does implicitly for you.  In fact, this:&lt;pre&gt;plumHallRope.accuse();&lt;/pre&gt;equates to&lt;pre&gt;plumHallRope.accuse.call(plumHallRope);&lt;/pre&gt;Now all three of the parts we identified above are shown distinctly: Getting the function reference from the property (&lt;code&gt;&lt;span style="font-weight:bold;"&gt;plumHallRope.accuse&lt;/span&gt;&lt;/code&gt;) is distinct from the fact we're calling it (&lt;code&gt;&lt;span style="font-weight:bold;"&gt;call&lt;/span&gt;&lt;/code&gt;) is distinct from what "this" should be (&lt;code&gt;&lt;span style="font-weight:bold;"&gt;(plumHallRope)&lt;/span&gt;&lt;/code&gt;).  The fact that these are distinct can be made clearer:&lt;pre&gt;var f;&lt;br /&gt;f = plumHallRope.accuse;&lt;br /&gt;f.call(plumHallRope);&lt;/pre&gt;Alternately, here's a more dramatic example:&lt;pre&gt;function testGuess3()&lt;br /&gt;{&lt;br /&gt;    var plumHallRope;&lt;br /&gt;    var fakeGuess;&lt;br /&gt;&lt;br /&gt;    plumHallRope = new Guess(&lt;br /&gt;        'Professor Plum',&lt;br /&gt;        'hall',&lt;br /&gt;        'rope');&lt;br /&gt;    plumHallRope.accuse();&lt;br /&gt;&lt;br /&gt;    fakeGuess = {};&lt;br /&gt;    fakeGuess.location = 'library';&lt;br /&gt;    fakeGuess.killer = 'Mrs. Peacock';&lt;br /&gt;    fakeGuess.weapon = 'revolver';&lt;br /&gt;&lt;br /&gt;    plumHallRope.accuse.call(fakeGuess);&lt;br /&gt;}&lt;/pre&gt;Not to bang on about it, but the call at the end accuses Mrs. Peacock, not Professor Plum. The &lt;code&gt;plumHallRope&lt;/code&gt; instance was only used to get the function reference, it wasn't used within the function call.  In our original &lt;code&gt;&lt;span style="font-weight:bold;"&gt;testGuess&lt;/span&gt;&lt;/code&gt; function, we could even do this if we wanted to:&lt;pre&gt;mustardStudyLeadPipe.accuse.call(plumHallRope);&lt;/pre&gt;Which accuses Professor Plum.  But it's more convenient, isn't it, to say &lt;code&gt;&lt;span style="font-weight:bold;"&gt;plumHallRope.accuse&lt;/span&gt;&lt;/code&gt;?&lt;br /&gt;&lt;br /&gt;So if "this" is really just a sort of obscure function argument, why have it? Why not just write everything as global functions and pass in the object to act on as the first argument? We could do that (and in fact I did it for years, as a C programmer), but it's more cumbersome. You have to know what functions are meant to be used with what kinds of objects, there's all sorts of stuff littering up the global namespace, etc., etc. By passing around object references, which have properties on them (usually inherited from their prototype; again the topic of an upcoming post) that reference functions intended for use with them, it's just so much more convenient.&lt;br /&gt;&lt;br /&gt;Okay, but what was that about that URL showing up earlier when we called &lt;code&gt;&lt;span style="font-weight:bold;"&gt;accuse&lt;/span&gt;&lt;/code&gt;? You'll remember earlier when we ran this code:&lt;pre&gt;    accuse = mustardStudyLeadPipe.accuse;&lt;br /&gt;    accuse();&lt;/pre&gt;we got the alert with the URL in it. So why did that happen, and where did the URL come from?  It was because we didn't give an object to use for "this", and so the function call got the default, which is the JavaScript global object. In browser implementations, the global object is the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;window&lt;/span&gt;&lt;/code&gt; object&amp;nbsp;-- so we were showing the values of window.killer, window.location, and window.weapon. In a typical situation, &lt;code&gt;&lt;span style="font-weight:bold;"&gt;window.killer&lt;/span&gt;&lt;/code&gt; and &lt;code&gt;&lt;span style="font-weight:bold;"&gt;window.weapon&lt;/span&gt;&lt;/code&gt; will be undefined, and of course &lt;code&gt;&lt;span style="font-weight:bold;"&gt;window.location&lt;/span&gt;&lt;/code&gt; is the URL of the document in the window.&lt;br /&gt;&lt;br /&gt;I chose that example intentionally, because it's a pitfall people fall into a lot: Losing "this". Usually, people lose "this" in the context of an event handler&amp;nbsp;-- e.g., they have an instance (&lt;code&gt;&lt;span style="font-weight:bold;"&gt;plumHallRope&lt;/span&gt;&lt;/code&gt;, perhaps), and want to hook up a "method" on it (say, &lt;code&gt;&lt;span style="font-weight:bold;"&gt;accuse&lt;/span&gt;&lt;/code&gt;) to an event (a click handler for a button, maybe?), and so understandably they do something like this (I'm again using convenience syntax, as I describe &lt;a href="http://blog.niftysnippets.org/2008/03/convenience-syntax-in-examples.html"&gt;here&lt;/a&gt;):&lt;pre&gt;Event.observe('theButton', plumHallRope.accuse); // WRONG&lt;/pre&gt;The problem being, that just references the &lt;span style="font-style:italic;"&gt;function&lt;/span&gt;, nothing about its context.  Its context will be determined by how it's called. Earlier when we called &lt;code&gt;&lt;span style="font-weight:bold;"&gt;accuse&lt;/span&gt;&lt;/code&gt; directly, because we didn't use dotted notation or &lt;code&gt;&lt;span style="font-weight:bold;"&gt;call&lt;/span&gt;&lt;/code&gt; or &lt;code&gt;&lt;span style="font-weight:bold;"&gt;apply&lt;/span&gt;&lt;/code&gt;, "this" was the global object; event handlers like this one will usually get "this" set to the element (although not if you're using old DOM0&amp;nbsp;-- onclick attribute&amp;nbsp;-- events or IE's &lt;code&gt;&lt;span style="font-weight:bold;"&gt;attachEvent&lt;/span&gt;&lt;/code&gt; function). To maintain its context, you have to do something like this:&lt;pre&gt;Event.observe('theButton', function() { plumHallRope.accuse(); });&lt;/pre&gt;The function that gets called by the event handler then turns around and calls the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;accuse&lt;/span&gt;&lt;/code&gt; function such that &lt;code&gt;&lt;span style="font-weight:bold;"&gt;plumHallRope&lt;/span&gt;&lt;/code&gt; is "this", so you've preserved "this" using a wrapper (which is also a closure; &lt;a href="http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html"&gt;details&lt;/a&gt;). (Note that thanks to a bug in Internet Explorer, that may well cause a memory leak for your IE users. &lt;a href="http://www.prototypejs.org/"&gt;Prototype&lt;/a&gt;'s &lt;a href="http://www.prototypejs.org/api/event/observe"&gt;&lt;code&gt;&lt;span style="font-weight:bold;"&gt;Event.observe()&lt;/span&gt;&lt;/code&gt;&lt;/a&gt; does some things to minimize the issue; other frameworks will have other helpers along those lines.)&lt;br /&gt;&lt;br /&gt;In Conclusion:&lt;br /&gt;&lt;br /&gt;I've seen people deride JavaScript for having "fake" methods, but I think that's missing the point. It doesn't have fake methods, it just doesn't have methods at all. What it &lt;span style="font-weight:bold;"&gt;does&lt;/span&gt; have is very powerful, flexible functions and some convenient syntactic sugar that lets us express the 90% case&amp;nbsp;-- calling a function related to an object instance passing in that object instance as an argument&amp;nbsp;-- in a compact and expressive way, but without limiting our use of the functions involved.  By not limiting our use, we can use just about anything as a &lt;a href="http://en.wikipedia.org/wiki/Mixin"&gt;mixin&lt;/a&gt;, we can use &lt;a href="http://en.wikipedia.org/wiki/Duck_typing"&gt;duck typing&lt;/a&gt;, easily create wrapper objects to enforce or verify &lt;a href="http://en.wikipedia.org/wiki/Design_by_contract"&gt;contracts&lt;/a&gt;, etc.&lt;br /&gt;&lt;br /&gt;Like so many things about the language, it's confusing until you grok just how simple it is, and then you start appreciating that it's simple but powerful.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-3456807625915222681?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/yD1-h43qmn8" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/yD1-h43qmn8/mythical-methods.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/03/mythical-methods.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-2769376066560065227</guid><pubDate>Mon, 24 Mar 2008 18:15:00 +0000</pubDate><atom:updated>2009-12-09T07:36:53.313Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">Prototype</category><category domain="http://www.blogger.com/atom/ns#">meta</category><title>Convenience Syntax in Examples</title><description>This is a "meta" post, e.g., it's about the blog itself.&lt;br /&gt;&lt;br /&gt;In many of my posts, I give code examples to illustrate a point.  To avoid cluttering the examples up with browser-specific stuff, I'm using a couple of calls from the &lt;a href="http://www.prototypejs.org"&gt;Prototype&lt;/a&gt; library.&lt;br /&gt;&lt;br /&gt;Actually, right now, just the one:  &lt;a href="http://www.prototypejs.org/api/event/observe"&gt;&lt;code&gt;&lt;span style="font-weight:bold;"&gt;Event.observe()&lt;/span&gt;&lt;/code&gt;&lt;/a&gt;.  This function hooks up an event handler in a way that is consistent across browsers, even Internet Explorer, which is good because IE doesn't support the standard &lt;a href="https://developer.mozilla.org/en/DOM/element.addEventListener"&gt;&lt;code&gt;&lt;span style="font-weight:bold;"&gt;addEventListener()&lt;/span&gt;&lt;/code&gt;&lt;/a&gt; function, and its own &lt;a href="http://msdn2.microsoft.com/en-us/library/ms536343(VS.85).aspx"&gt;&lt;code&gt;&lt;span style="font-weight:bold;"&gt;attachEvent()&lt;/span&gt;&lt;/code&gt;&lt;/a&gt; function behaves slightly differently (within the handler, "this" is the global object, like in old DOM0 handlers; whereas with &lt;code&gt;&lt;span style="font-weight:bold;"&gt;addEventListener&lt;/span&gt;&lt;/code&gt; it's the element you're hooking the event to).  Prototype's &lt;code&gt;&lt;span style="font-weight:bold;"&gt;Event.observe()&lt;/span&gt;&lt;/code&gt; ensures that "this" is always the element, even on IE, and also does some housekeeping to try to mitigate an IE bug where it tends to leak memory if you use closures as event handlers (which is incredibly common).&lt;br /&gt;&lt;br /&gt;If I use more Prototype stuff, I'll list it here as well, but this is only about trying to keep the examples simple and clear, not about using Prototype or any other specific library...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-2769376066560065227?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/hNm9JLrzjWQ" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/hNm9JLrzjWQ/convenience-syntax-in-examples.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/03/convenience-syntax-in-examples.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-1044054371320864804</guid><pubDate>Tue, 18 Mar 2008 14:40:00 +0000</pubDate><atom:updated>2008-06-09T09:51:53.342+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">JavaScript</category><category domain="http://www.blogger.com/atom/ns#">scope</category><category domain="http://www.blogger.com/atom/ns#">var</category><category domain="http://www.blogger.com/atom/ns#">pitfall</category><title>The horror of implicit globals</title><description>This code should cause an error, right?&lt;pre&gt;function doSomething()&lt;br /&gt;{&lt;br /&gt;    var x;&lt;br /&gt;&lt;br /&gt;    x = 10;&lt;br /&gt;    y = 20;&lt;br /&gt;&lt;br /&gt;    alert('x = ' + x);&lt;br /&gt;    alert('y = ' + y);&lt;br /&gt;}&lt;/pre&gt;Well, you'd think so, wouldn't you? (There's no declaration for &lt;code&gt;&lt;span style="font-weight:bold;"&gt;y&lt;/span&gt;&lt;/code&gt;.) It doesn't, though. It also probably doesn't do what the author intended. Welcome to the horror of implicit globals. The good news is that there's something we can do about it.&lt;br /&gt;&lt;br /&gt;So what did the code &lt;span style="font-style:italic;"&gt;really&lt;/span&gt; do? Well, in a simple test, it would &lt;span style="font-style:italic;"&gt;seem&lt;/span&gt; to do what the author intended, in that it shows two alerts:&lt;ul&gt;&lt;li&gt;x = 10&lt;/li&gt;&lt;li&gt;y = 20&lt;/li&gt;&lt;/ul&gt;But &lt;code&gt;&lt;span style="font-weight:bold;"&gt;x&lt;/span&gt;&lt;/code&gt; and &lt;code&gt;&lt;span style="font-weight:bold;"&gt;y&lt;/span&gt;&lt;/code&gt; are completely different; &lt;code&gt;&lt;span style="font-weight:bold;"&gt;x&lt;/span&gt;&lt;/code&gt; is a local variable within the function, whereas &lt;code&gt;&lt;span style="font-weight:bold;"&gt;y&lt;/span&gt;&lt;/code&gt; is created as a "global variable". Said "global variable" is not declared anywhere at all, it exists purely because it was assigned to by this function. Functions can create global variables willy-nilly with no advance declaration or indeed, with no declaration at all.&lt;br /&gt;&lt;br /&gt;This is clearly a Bad Thing, so why would the language designers let it happen? Well, in some sense I think it's a side-effect. To see why we have the possibility of implicit globals, we have to delve into objects and properties.&lt;br /&gt;&lt;br /&gt;If you've done any JavaScript stuff with objects, you know that you can assign a property to an object simply by, well, assigning it:&lt;pre&gt;myobject.myprop = 5;&lt;/pre&gt;This sets the property &lt;code&gt;&lt;span style="font-weight:bold;"&gt;myprop&lt;/span&gt;&lt;/code&gt; on the object &lt;code&gt;&lt;span style="font-weight:bold;"&gt;myobject&lt;/span&gt;&lt;/code&gt;, creating a new property if the property didn't exist before. This is simple, it's convenient, and it's part of the power of JavaScript that objects can just acquire properties without any preamble.&lt;br /&gt;&lt;br /&gt;But what does this have to do with implicit global variables? Well, you see, JavaScript doesn't have global variables. No, seriously. It has a global object (just the one), and that object has properties. Those properties are what we &lt;span style="font-style:italic;"&gt;think of&lt;/span&gt; as global (or page-scope) variables. You might think that this is a distinction without a difference, but if it were, the code shown at the beginning of this post would fail because &lt;code&gt;&lt;span style="font-weight:bold;"&gt;y&lt;/span&gt;&lt;/code&gt; isn't declared. It doesn't fail, because by assigning &lt;code&gt;&lt;span style="font-weight:bold;"&gt;y&lt;/span&gt;&lt;/code&gt; a value, we created a property on the global object.&lt;br /&gt;&lt;br /&gt;"Now hang on," you're saying, "there's nothing in that code referencing some kind of 'global object'." Ah, but there is. And that brings us to the &lt;span style="font-style:italic;"&gt;scope chain&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;I've mentioned the scope chain &lt;a href="http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html"&gt;before&lt;/a&gt;. The scope chain is how JavaScript resolves unqualified references: In any given execution context (e.g., global code or function), there is a chain of objects that the JavaScript engine looks to when resolving an unqualified reference: It first checks to see if the top object has a property with the given name, and uses that property if it does; if not, it checks the next object in the chain, etc. The global object is always the last object in the chain. If the engine gets all the way down to the global object and we're assigning a value to the unqualified reference, the reference is assigned as a property of the global object. And since properties don't have to be declared in advance, voil&amp;aacute;, implicit globals.&lt;br /&gt;&lt;br /&gt;We can see this in practice. The &lt;a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm"&gt;JavaScript specification&lt;/a&gt; says simply that there &lt;span style="font-style:italic;"&gt;is&lt;/span&gt; a global object and that it's always the root of the scope chain, but it doesn't say what it is&amp;nbsp;-- which makes sense as JavaScript is a general-purpose language. In browser-based implementations, though, the global object has a name: &lt;span style="font-weight:bold;"&gt;window&lt;/span&gt;. Technically, the symbol &lt;code&gt;&lt;span style="font-weight:bold;"&gt;window&lt;/span&gt;&lt;/code&gt; in browser-based JavaScript is a &lt;span style="font-style:italic;"&gt;property&lt;/span&gt; of the global object that refers to the object itself. I mention this not only because it's useful to know, but because it lets us prove to ourselves that "global variables" are really properties of the global object. Let's add a line to our code from above:&lt;pre&gt;function doSomething()&lt;br /&gt;{&lt;br /&gt;    var x;&lt;br /&gt;&lt;br /&gt;    x = 10;&lt;br /&gt;    y = 20;&lt;br /&gt;&lt;br /&gt;    alert('x = ' + x);&lt;br /&gt;    alert('y = ' + y);&lt;br /&gt;    &lt;span style="font-weight:bold;"&gt;alert('window.y = ' + window.y);&lt;/span&gt;&lt;br /&gt;}&lt;/pre&gt;This starts out by showing the same two alerts we had before:&lt;ul&gt;&lt;li&gt;x = 10&lt;/li&gt;&lt;li&gt;y = 20&lt;/li&gt;&lt;/ul&gt;...and then it shows a third:&lt;ul&gt;&lt;li&gt;window.y = 20&lt;/li&gt;&lt;/ul&gt;...because &lt;code&gt;&lt;span style="font-weight:bold;"&gt;y&lt;/span&gt;&lt;/code&gt; and &lt;code&gt;&lt;span style="font-weight:bold;"&gt;window.y&lt;/span&gt;&lt;/code&gt; both refer to the same property of the same object, the global object.&lt;br /&gt;&lt;br /&gt;All of this holds true even if we do declare &lt;code&gt;&lt;span style="font-weight:bold;"&gt;y&lt;/span&gt;&lt;/code&gt; at global scope:&lt;pre&gt;&lt;span style="font-weight:bold;"&gt;var y;&lt;/span&gt;&lt;br /&gt;function doSomething()&lt;br /&gt;{&lt;br /&gt;    var x;&lt;br /&gt;&lt;br /&gt;    x = 10;&lt;br /&gt;    y = 20;&lt;br /&gt;&lt;br /&gt;    alert('x = ' + x);&lt;br /&gt;    alert('y = ' + y);&lt;br /&gt;    alert('window.y = ' + window.y);&lt;br /&gt;}&lt;/pre&gt;This shows the same three alerts shown earlier. &lt;span style="font-style:italic;"&gt;(There is a very slight technical difference between declared and undeclared globals that relates to the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;delete&lt;/span&gt;&lt;/code&gt; statement, but the distinction isn't important here, it's just a flag on the property.)&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Now, some readers will be thinking "Cool! This means I don't have to have 'var' statements for my globals! I can save a bit of space on the downloaded script files!"  Well, true, you could. It's an awfully bad idea, though. Not only would it be a bit unfriendly to anyone else trying to read your script (I suppose you could address that somewhat with comments that get stripped out before download), but it would also mean you couldn't use any &lt;a href="http://en.wikipedia.org/wiki/Lint_%28software%29"&gt;lint&lt;/a&gt; tools, and you really, really want to. Because the ramification of all of this is that a simple typo, perhaps:&lt;pre&gt;thigny = 10;&lt;/pre&gt;instead of&lt;pre&gt;thingy = 10;&lt;/pre&gt;can create a new global variable in your page, introducing a bug that's &lt;span style="font-style:italic;"&gt;awfully&lt;/span&gt; hard to find. Fortunately, though, people have created &lt;a href="http://www.javascriptlint.com/"&gt;various&lt;/a&gt; &lt;a href="http://www.jslint.com/"&gt;tools&lt;/a&gt; to do lint checking on JavaScript, tools that can find that error for you before you even get to the testing stage, much less production.&lt;br /&gt;&lt;br /&gt;And so there we are, the horror of implicit globals&amp;nbsp;-- and the relief of knowing that we have a defense against them!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-1044054371320864804?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/a9FTMBmAm5k" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/a9FTMBmAm5k/horror-of-implicit-globals.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-6105645211848323190</guid><pubDate>Mon, 17 Mar 2008 13:32:00 +0000</pubDate><atom:updated>2008-03-17T13:36:18.112Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">meta</category><title>Now at blog.niftysnippets.org</title><description>Just briefly, this blog is now at &lt;a href="http://blog.niftysnippets.org"&gt;http://blog.niftysnippets.org&lt;/a&gt;, rather than http://niftysnippets.blogspot.com.  It's still hosted by Blogger (for now), and Blogger is kind enough to forward you from the old address, but if for some reason you're a regular reader of this blog, it's worth updating your Atom/RSS links just in case someday I end up hosting it myself or moving to Wordpress or something...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-6105645211848323190?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/84laiQam52w" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/84laiQam52w/now-at-blogniftysnippetsorg.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/03/now-at-blogniftysnippetsorg.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-3393811840522767991</guid><pubDate>Mon, 17 Mar 2008 11:52:00 +0000</pubDate><atom:updated>2008-03-17T13:32:41.163Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">JavaScript</category><category domain="http://www.blogger.com/atom/ns#">scope</category><title>When you absolutely, positively need new scope</title><description>Just a quick one today, one that in many ways is a solution in search of a problem... ;-)&lt;br /&gt;&lt;br /&gt;As you probably know, in most of the languages with vaguely C-like syntax (C, C++, Java, C#, ...), a new block introduces new scope.  E.g., this Java code:&lt;pre&gt;String myJavaMethod()&lt;br /&gt;{&lt;br /&gt;    String s;&lt;br /&gt;&lt;br /&gt;    s = "outer string";&lt;br /&gt;&lt;br /&gt;    {&lt;br /&gt;        String s;&lt;br /&gt;&lt;br /&gt;        s = "inner string";&lt;br /&gt;&lt;br /&gt;        // (Presumably do something with 's' in here)&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return s;&lt;br /&gt;}&lt;/pre&gt;...while strange, is perfectly valid. It returns a String with the text "outer string".  The &lt;code&gt;&lt;span style="font-weight:bold;"&gt;s&lt;/span&gt;&lt;/code&gt; variable declared within the inner block is scoped only to the inner block.&lt;br /&gt;&lt;br /&gt;A similar-looking JavaScript function has a completely different result:&lt;pre&gt;function myJavaScriptMethod()&lt;br /&gt;{&lt;br /&gt;    var s;&lt;br /&gt;&lt;br /&gt;    s = "outer string";&lt;br /&gt;&lt;br /&gt;    {&lt;br /&gt;        var s;&lt;br /&gt;&lt;br /&gt;        s = "inner string";&lt;br /&gt;&lt;br /&gt;        // (Presumably do something with 's' in here)&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return s;&lt;br /&gt;}&lt;/pre&gt;It's still valid, but it returns the string "inner string" rather than "outer string". Blocks do not introduce new scope in JavaScript, only functions do that. (If you're thinking that the second &lt;code&gt;&lt;span style="font-weight:bold;"&gt;var&lt;/span&gt;&lt;/code&gt; declaration should be an error, well, I agree&amp;nbsp;-- but it isn't, details &lt;a href="http://blog.niftysnippets.org/2008/03/poor-misunderstood-var.html"&gt;here&lt;/a&gt;.)&lt;br /&gt;&lt;br /&gt;But what if you absolutely, positively need new scope within a function? It's actually pretty easy to achieve; just use a closure. If I really needed my JavaScript function above to behave like the Java version, I could rewrite it like this:&lt;pre&gt;function myJavaScriptMethodUpdated()&lt;br /&gt;{&lt;br /&gt;    var s;&lt;br /&gt;&lt;br /&gt;    s = "outer string";&lt;br /&gt;&lt;br /&gt;    (function()&lt;br /&gt;    {&lt;br /&gt;        var s;&lt;br /&gt;&lt;br /&gt;        s = "inner string";&lt;br /&gt;&lt;br /&gt;        // (Presumably do something with 's' in here)&lt;br /&gt;    })();&lt;br /&gt;&lt;br /&gt;    return s;&lt;br /&gt;}&lt;/pre&gt;Looks weird, eh? What I've done is create an anonymous inline function and then immediately execute it. Since it's a closure (all JavaScript functions are closures), it has access to all of the arguments and variables defined in its containing function except for the ones it's masked by declaring its own (which it's done with &lt;code&gt;&lt;span style="font-weight:bold;"&gt;s&lt;/span&gt;&lt;/code&gt;).&lt;br /&gt;&lt;br /&gt;Naturally, as this is defining and calling a function, there's a performance aspect although setting up a function call should be fairly quick in any decent JavaScript implementation&amp;nbsp;-- and again, you're only doing this when you absolutely, positively need new scope, right?&lt;br /&gt;&lt;br /&gt;So, okay, how is this useful? Well, as I say, this may well be a solution in search of a problem. It mostly gave me an excuse to highlight the fact that blocks don't introduce new scope in JavaScript. And frankly, in most cases if you need to set up new scope within a function like that, it probably means you haven't broken things up into small enough pieces; if you do that, you'll probably find that you &lt;span style="font-style:italic;"&gt;don't&lt;/span&gt; absolutely, positively need new scope because your pieces are small enough that things are scoped properly.&lt;br /&gt;&lt;br /&gt;That said, though, think in terms of sandboxing and namespacing&amp;nbsp;-- if you wrap an entire external library in a closure and then execute that closure, any globally-declared vars in that library become local variables within the closure and can't conflict with others defined at global scope. So there may be something useful there, although it's far from a real sandboxing or namespacing solution...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-3393811840522767991?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/5N8AOmvtibE" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/5N8AOmvtibE/when-you-absolutely-positively-need-new.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/03/when-you-absolutely-positively-need-new.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-5949233004039052236</guid><pubDate>Sun, 16 Mar 2008 11:09:00 +0000</pubDate><atom:updated>2008-03-26T11:45:07.672Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">design</category><title>A simple point about design</title><description>A &lt;a href="http://jockmurphy.com"&gt;good friend of mine&lt;/a&gt; pointed me at &lt;a href="http://stuffthathappens.com/blog/2008/03/05/simplicity/"&gt;this comic&lt;/a&gt; and I just had to share it. I've rarely seen this point put more...simply.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-5949233004039052236?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/AtSh-c4egrU" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/AtSh-c4egrU/slightly-off-topic.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/03/slightly-off-topic.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-2341573448995158355</guid><pubDate>Sat, 15 Mar 2008 15:00:00 +0000</pubDate><atom:updated>2008-03-25T14:22:38.626Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">JavaScript</category><category domain="http://www.blogger.com/atom/ns#">closures</category><category domain="http://www.blogger.com/atom/ns#">scope</category><title>Closures by example</title><description>In an &lt;a href="http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html"&gt;earlier post&lt;/a&gt;, I promised a follow-up with a few examples of closures. Before we get to the examples, a quick note: To avoid cluttering things up with browser-specific stuff, I'm using the &lt;a href="http://www.prototypejs.org/api/event/observe"&gt;&lt;code&gt;&lt;span style="font-weight:bold;"&gt;Event.observe()&lt;/span&gt;&lt;/code&gt;&lt;/a&gt; method from &lt;a href="http://www.prototypejs.org/"&gt;Prototype&lt;/a&gt;. &lt;code&gt;&lt;span style="font-weight:bold;"&gt;Event.observe()&lt;/span&gt;&lt;/code&gt; hooks up an event handler, allowing for differences between browser implementations (see the link for more detail).&lt;br /&gt;&lt;br /&gt;I have to say that I found this post to be a real challenge, and it took me a while to figure out why:  I kept trying to boil things down to their essence, and the fact is that if you do that, you end up with a single example, one that demonstrates that a closure function has access to intrinsic data.  And let's face it, that's not very interesting. :-)&lt;br /&gt;&lt;br /&gt;So rather than boil things down, I'll give a few examples of where closures frequently get used, even though they all pretty much demonstrate the same fundamental point (about the functions having intrinsic data).&lt;br /&gt;&lt;br /&gt;Okay, to the examples:&lt;ol&gt;&lt;li&gt;&lt;a href='#boundevent'&gt;A Simple Bound Event Handler&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='#enduring'&gt;Enduring References&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='#enduringtowhat'&gt;Enduring References to &lt;span style="font-style:italic;"&gt;What&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='#privateprops'&gt;Private Properties&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='#callbacks'&gt;Callbacks&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='#inadvertent'&gt;The Inadvertent Closure (an anti-pattern)&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href='#yours'&gt;Your Examples&lt;/a&gt;&lt;/li&gt;&lt;/ol&gt;&lt;a name='boundevent'&gt;&lt;/a&gt;&lt;span style="font-weight:bold;"&gt;#1: A Simple Bound Event Handler&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;One of the most common uses of closures is to bind a function and some data to an event handler:&lt;br /&gt;&lt;pre&gt;function wireUpMessage(element, msg)&lt;br /&gt;{&lt;br /&gt;    Event.observe(&lt;br /&gt;        element,&lt;br /&gt;        'click',&lt;br /&gt;        &lt;span style="font-weight:bold;"&gt;function()&lt;br /&gt;        {&lt;br /&gt;            alert(msg);&lt;br /&gt;        }&lt;/span&gt;&lt;br /&gt;    );&lt;br /&gt;}&lt;/pre&gt;This &lt;code&gt;&lt;span style="font-weight:bold;"&gt;wireUpMessage&lt;/span&gt;&lt;/code&gt; function creates a closure (the bit in bold) and hooks it up to the "click" event of the given element, having it show the given message. The closure keeps a reference to the arguments and variables in scope where it was defined, so it has access to the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;msg&lt;/span&gt;&lt;/code&gt; argument we passed the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;wireUpMessage&lt;/span&gt;&lt;/code&gt; function, even though that function has returned.&lt;br /&gt;&lt;br /&gt;Assuming we have a button with the ID "btnSayHey", we can use this as follows:&lt;pre&gt;wireUpMessage('btnSayHey', 'Hey there');&lt;/pre&gt;Try it out:&lt;br /&gt;&lt;br /&gt;&lt;input type='button' id='btnSayHey' value='Say hey'/&gt;&lt;br /&gt;&lt;br /&gt;&lt;a name='enduring'&gt;&lt;/a&gt;&lt;span style="font-weight:bold;"&gt;#2: Enduring References&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;You could easily get the idea from the previous example that the closure we created somehow had the text "Hey there" bound into it &lt;span style="font-style:italic;"&gt;literally&lt;/span&gt;. That's not true. It's the reference to the context containing the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;msg&lt;/span&gt;&lt;/code&gt; argument that's bound to the closure, not the value of that argument. The &lt;code&gt;&lt;span style="font-weight:bold;"&gt;msg&lt;/span&gt;&lt;/code&gt; argument's value is evaluated when the closure is &lt;span style="font-style:italic;"&gt;executed&lt;/span&gt;, not when it's defined. This is important, powerful, and frequently misunderstood. ;-)&lt;br /&gt;&lt;br /&gt;Consider this:&lt;pre&gt;function setupCounterButtons(startBtnName, showBtnName, stopBtnName)&lt;br /&gt;{&lt;br /&gt;    var counter;&lt;br /&gt;    var intid;&lt;br /&gt;&lt;br /&gt;    counter = 0;&lt;br /&gt;    intid = undefined;&lt;br /&gt;&lt;br /&gt;    function startCounter()&lt;br /&gt;    {&lt;br /&gt;        stopCounter();&lt;br /&gt;        counter = 0;&lt;br /&gt;        intid = window.setInterval(function() { ++counter; }, 200);&lt;br /&gt;    }&lt;br /&gt;    function stopCounter()&lt;br /&gt;    {&lt;br /&gt;        if (intid !== undefined)&lt;br /&gt;        {&lt;br /&gt;            window.clearInterval(intid);&lt;br /&gt;            intid = undefined;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    function showCounter()&lt;br /&gt;    {&lt;br /&gt;        var msg;&lt;br /&gt;&lt;br /&gt;        msg = "Counter = " + counter + " (";&lt;br /&gt;        if (intid === undefined)&lt;br /&gt;        {&lt;br /&gt;            msg += "not ";&lt;br /&gt;        }&lt;br /&gt;        msg += "running)";&lt;br /&gt;        alert(msg);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    Event.observe(&lt;br /&gt;        document.getElementById(startBtnName),&lt;br /&gt;        'click',&lt;br /&gt;        startCounter&lt;br /&gt;    );&lt;br /&gt;    Event.observe(&lt;br /&gt;        document.getElementById(showBtnName),&lt;br /&gt;        'click',&lt;br /&gt;        showCounter&lt;br /&gt;    );&lt;br /&gt;    Event.observe(&lt;br /&gt;        document.getElementById(stopBtnName),&lt;br /&gt;        'click',&lt;br /&gt;        stopCounter&lt;br /&gt;    );&lt;br /&gt;}&lt;/pre&gt;This function has the local variables &lt;code&gt;&lt;span style="font-weight:bold;"&gt;counter&lt;/span&gt;&lt;/code&gt; and &lt;code&gt;&lt;span style="font-weight:bold;"&gt;intid&lt;/span&gt;&lt;/code&gt;, three named functions (which are closures), and a fourth anonymous closure we've passed into &lt;code&gt;&lt;span style="font-weight:bold;"&gt;window.setInterval&lt;/span&gt;&lt;/code&gt;. The named functions are: &lt;code&gt;&lt;span style="font-weight:bold;"&gt;startCounter&lt;/span&gt;&lt;/code&gt;, which starts a 200ms repeating update of the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;counter&lt;/span&gt;&lt;/code&gt; local variable; &lt;code&gt;&lt;span style="font-weight:bold;"&gt;showCounter&lt;/span&gt;&lt;/code&gt;, which displays the current &lt;code&gt;&lt;span style="font-weight:bold;"&gt;counter&lt;/span&gt;&lt;/code&gt; value; and &lt;code&gt;&lt;span style="font-weight:bold;"&gt;stopCounter&lt;/span&gt;&lt;/code&gt;, which stops the 200ms update. It hooks these functions up to the buttons whose names we pass into the function. So if we hook up the buttons 'btnStartCounter1', 'btnShowCounter1', 'btnStopCounter1' with this code:&lt;pre&gt;setupCounterButtons('btnStartCounter1', 'btnShowCounter1', 'btnStopCounter1');&lt;/pre&gt;...we get to try it out:&lt;br /&gt;&lt;br /&gt;&lt;input type='button' id='btnStartCounter1' value='Start Counter 1'/&gt;&lt;input type='button' id='btnShowCounter1' value='Show Counter 1'/&gt;&lt;input type='button' id='btnStopCounter1' value='Stop Counter 1'/&gt;&lt;br /&gt;&lt;br /&gt;This demonstrates two important things: Firstly, the closures have an ongoing &lt;span style="font-style:italic;"&gt;reference&lt;/span&gt; to the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;counter&lt;/span&gt;&lt;/code&gt; variable, not its literal value where they're defined. Secondly, all of the closures are referencing the &lt;span style="font-style:italic;"&gt;same&lt;/span&gt; context: When &lt;code&gt;&lt;span style="font-weight:bold;"&gt;startCounter&lt;/span&gt;&lt;/code&gt; sets the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;counter&lt;/span&gt;&lt;/code&gt; and &lt;code&gt;&lt;span style="font-weight:bold;"&gt;intid&lt;/span&gt;&lt;/code&gt; values, &lt;code&gt;&lt;span style="font-weight:bold;"&gt;showCounter&lt;/span&gt;&lt;/code&gt; sees those changes; when the closure we've enabled via &lt;code&gt;&lt;span style="font-weight:bold;"&gt;window.setInterval&lt;/span&gt;&lt;/code&gt; updates &lt;code&gt;&lt;span style="font-weight:bold;"&gt;counter&lt;/span&gt;&lt;/code&gt;, we see that update. All closures defined in the same context share access to that &lt;span style="font-style:italic;"&gt;same&lt;/span&gt; context.&lt;br /&gt;&lt;br /&gt;&lt;a name='enduringtowhat'&gt;&lt;/a&gt;&lt;span style="font-weight:bold;"&gt;#3: Enduring References to &lt;span style="font-style:italic;"&gt;What&lt;/span&gt;?&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Look again at the previous example and think for a moment about what it is that the closures have access to, which endures even after the setup function has completed.  Is it something unique attached to the setup function? Well, if that were true, what would happen if I called the function again and hooked it up to different buttons; would those buttons control and access the same counter that the first set of buttons do? If your impulse is to say "yes," consider that &lt;code&gt;&lt;span style="font-weight:bold;"&gt;counter&lt;/span&gt;&lt;/code&gt; is a &lt;span style="font-style:italic;"&gt;local variable&lt;/span&gt; within the function. Local variables aren't specific to the function for all eternity, right? They only relate to a specific time you've &lt;span style="font-style:italic;"&gt;called&lt;/span&gt; that function.  So if we call it again...yup, that's it, we get a new context, and the closures within that context access that new context, not the previous one.&lt;br /&gt;&lt;br /&gt;And so if we hook up a new set of buttons:&lt;pre&gt;setupCounterButtons('btnStartCounter2', 'btnShowCounter2', 'btnStopCounter2');&lt;/pre&gt;We get a second counter. Try it out and see whether there's any interaction between the counter controlled by these buttons:&lt;br /&gt;&lt;br /&gt;&lt;input type='button' id='btnStartCounter2' value='Start Counter 2'/&gt;&lt;input type='button' id='btnShowCounter2' value='Show Counter 2'/&gt;&lt;input type='button' id='btnStopCounter2' value='Stop Counter 2'/&gt;&lt;br /&gt;&lt;br /&gt;...and the one controlled by the buttons in the previous example.&lt;br /&gt;&lt;br /&gt;Right, there isn't any, because they're referencing different counters.&lt;br /&gt;&lt;br /&gt;&lt;a name='privateprops'&gt;&lt;/a&gt;&lt;span style="font-weight:bold;"&gt;#4: Private Properties&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Lots of JavaScript apps these days make extensive use of object orientation. One key OOP principle is &lt;a href="http://en.wikipedia.org/wiki/Information_hiding"&gt;information hiding&lt;/a&gt;. There are several good reasons for information hiding. One example is to defend against an object instance having an invalid state. Frequently this is done by having private data members and only allowing access to them via accessor methods that can prevent invalid values. Since all properties of JavaScript objects are public, how can we have private data members? The answer, of course, is to use closures, much as we did with the counters above. (Crockford is probably the first to document how you can do this, &lt;a href="http://javascript.crockford.com/private.html"&gt;here&lt;/a&gt;.)&lt;br /&gt;&lt;br /&gt;Here's an example, a Circle class that ensures that its radius is never allowed to become negative:&lt;pre&gt;function Circle(radius)&lt;br /&gt;{&lt;br /&gt;    this.setRadius = function(r)&lt;br /&gt;    {&lt;br /&gt;        if (r &lt; 0)&lt;br /&gt;        {&lt;br /&gt;            throw "Radius cannot be less than zero.";&lt;br /&gt;        }&lt;br /&gt;        radius = r;&lt;br /&gt;    };&lt;br /&gt;    this.getRadius = function()&lt;br /&gt;    {&lt;br /&gt;        return radius;&lt;br /&gt;    };&lt;br /&gt;&lt;br /&gt;    this.setRadius(radius);&lt;br /&gt;}&lt;/pre&gt;Note that we don't have a "&lt;span style="font-weight:bold;"&gt;radius&lt;/span&gt;" property on this object at all. This code:&lt;pre&gt;var c;&lt;br /&gt;c = new Circle(10);&lt;br /&gt;alert("Radius: " + c.radius); // undefined!!&lt;br /&gt;&lt;/pre&gt;Shows "&lt;span style="font-weight:bold;"&gt;Radius: undefined&lt;/span&gt;" because the property simply doesn't exist. Try it:&lt;br /&gt;&lt;br /&gt;&lt;input type='button' id='btnTestCircle1' value='Test Circle (1)' /&gt;&lt;br /&gt;&lt;br /&gt;Instead, the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;setRadius&lt;/span&gt;&lt;/code&gt; and &lt;code&gt;&lt;span style="font-weight:bold;"&gt;getRadius&lt;/span&gt;&lt;/code&gt; methods of the object are closures, both of which have a reference to the context in which they were defined, and they share that context as they were defined in the same scope. So rather than having a "&lt;span style="font-weight:bold;"&gt;radius&lt;/span&gt;" property, they simply use the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;radius&lt;/span&gt;&lt;/code&gt; parameter given to the constructor, which they keep a reference to even after the constructor has returned. Consequently, this code works just fine:&lt;pre&gt;var c;&lt;br /&gt;c = new Circle(10);&lt;br /&gt;alert("Radius before update: " + c.getRadius());&lt;br /&gt;c.setRadius(20);&lt;br /&gt;alert("Radius after update: " + c.getRadius());&lt;/pre&gt;Try it:&lt;br /&gt;&lt;br /&gt;&lt;input type='button' id='btnTestCircle2' value='Test Circle (2)' /&gt;&lt;br /&gt;&lt;br /&gt;(I should mention that there is a downside to this. When you do this, all Circle objects [for example] have their own copies of the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;setRadius&lt;/span&gt;&lt;/code&gt; and &lt;code&gt;&lt;span style="font-weight:bold;"&gt;getRadius&lt;/span&gt;&lt;/code&gt; functions, rather than sharing copies on an underlying Circle.prototype object. That's a whole different topic, though.)&lt;br /&gt;&lt;br /&gt;&lt;a name='callbacks'&gt;&lt;/a&gt;&lt;span style="font-weight:bold;"&gt;#5: Callbacks&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Closures get used as callbacks a &lt;span style="font-style:italic;"&gt;lot&lt;/span&gt;. Of course, event handlers are callbacks and so we've already talked about this, but it's useful to remember non-event-handler callbacks.&lt;br /&gt;&lt;br /&gt;One very common example is container objects that offer a method (usually called "each" or "forEach") that will call a callback once for each contained object. Prototype provides this (&lt;a href="http://www.prototypejs.org/api/enumerable/each"&gt;Enumerable.each&lt;/a&gt;) on arrays and several other objects; Dojo has something similar (&lt;a href="http://redesign.dojotoolkit.org/jsdoc/dojo/HEAD/dojo.forEach"&gt;dojo.forEach&lt;/a&gt;); JavaScript 1.6 defines this for arrays (&lt;a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:forEach"&gt;Array.forEach&lt;/a&gt;). So if we have an array (say) of &lt;code&gt;&lt;span style="font-weight:bold;"&gt;Person&lt;/span&gt;&lt;/code&gt; objects, we can act on each element like this (using Prototype syntax):&lt;pre&gt;personArray.each(&lt;br /&gt;    function(person)&lt;br /&gt;    {&lt;br /&gt;        // Do something with the 'person' object&lt;br /&gt;    }&lt;br /&gt;);&lt;/pre&gt;Suppose we wanted to build a sublist of only the people who are 65 and over:&lt;pre&gt;var sixtyFivePlus;&lt;br /&gt;sixtyFivePlus = [];&lt;br /&gt;personList.each(&lt;br /&gt;    function(person)&lt;br /&gt;    {&lt;br /&gt;        if (person.age &gt;= 65)&lt;br /&gt;        {&lt;br /&gt;            sixtyFivePlus.push(person);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;);&lt;/pre&gt;That uses a closure to add each 65-and-over person to the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;sixtyFivePlus&lt;/span&gt;&lt;/code&gt; array.&lt;br /&gt;&lt;br /&gt;In practice, closures are used like this in modern JavaScript all over the place.&lt;br /&gt;&lt;br /&gt;&lt;a name='inadvertent'&gt;&lt;/a&gt;&lt;span style="font-weight:bold;"&gt;#6: The Inadvertent Closure (an anti-pattern)&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;In Example #1, I said that a very common use of closures was to bind a function and some data to an event handler. Unfortunately, while it may literally be true that that's a very common use, I suspect many times it's not the &lt;span style="font-style:italic;"&gt;intent&lt;/span&gt; of the programmer creating the closure. I suspect much of the time, the programmer just wanted to bind the function, not any data, to the event handler, but didn't realize they were creating a closure and binding data as well.&lt;br /&gt;&lt;br /&gt;Unless a page author is using DOM Level 0 event handling (e.g., onclick attributes in the HTML markup), usually there's a setup function called on page load that hooks up event handlers to the buttons and such using some analog of the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;Event.observe&lt;/span&gt;&lt;/code&gt; function I've been using in this post. Sometimes those setup functions are dealing with large data sets, perhaps a big JSON or XML document retrieved via an XMLHttpRequest query, referencing that data with local variables. Then the event handlers are defined within the setup function, which means they're closures, which means...right, they keep a reference to the setup function's context, and so the large data set is retained in memory.&lt;br /&gt;&lt;br /&gt;Now, if that's on purpose&amp;nbsp;-- the page is referring back to it periodically, etc.&amp;nbsp;-- that's fine. But if the data set was just to be used for setup, it's a waste of memory. I call this the "Inadvertent Closure" &lt;a href="http://en.wikipedia.org/wiki/Anti-pattern"&gt;anti-pattern&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Here's an example:&lt;pre&gt;function mySetup()&lt;br /&gt;{&lt;br /&gt;    var setupData;&lt;br /&gt;    var n;&lt;br /&gt;&lt;br /&gt;    // Set 'setupData' to some large amount of data used only for setup;&lt;br /&gt;    // the below is just a contrived array.&lt;br /&gt;    setupData = [];&lt;br /&gt;    for (n = 0; n &lt; 1000; ++n)&lt;br /&gt;    {&lt;br /&gt;        setupData[n] = "Item " + n;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // (Presumably use the setup data for something here)&lt;br /&gt;&lt;br /&gt;    // Hook up some event handlers&lt;br /&gt;    Event.observe(&lt;br /&gt;        'someButton',&lt;br /&gt;        'click',&lt;br /&gt;        function()&lt;br /&gt;        {&lt;br /&gt;            // Do something interesting&lt;br /&gt;        }&lt;br /&gt;    );&lt;br /&gt;    Event.observe(&lt;br /&gt;        'someOtherButton',&lt;br /&gt;        'click',&lt;br /&gt;        function()&lt;br /&gt;        {&lt;br /&gt;            // Do something else interesting&lt;br /&gt;        }&lt;br /&gt;    );&lt;br /&gt;    // (Etc.)&lt;br /&gt;}&lt;/pre&gt;Here, a bunch of setup data is allocated and referenced via the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;setupData&lt;/span&gt;&lt;/code&gt; array, and then we hook up a couple of event handlers that &lt;span style="font-weight:bold;"&gt;don't&lt;/span&gt; need a reference to the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;setupData&lt;/span&gt;&lt;/code&gt; array.&lt;br /&gt;&lt;br /&gt;Well, they may not need it, but they have it, which means that all of that data is sitting around eating up memory unnecessarily.&lt;br /&gt;&lt;br /&gt;The good news is that it's easy to fix. There are at least two ways to fix it; the way I don't like, and the way I like. ;-)&lt;br /&gt;&lt;br /&gt;The way I &lt;span style="font-weight:bold;"&gt;don't&lt;/span&gt; like: Just "null out" the big data set when you're done with it; in our example, we'd just add this line to the end of the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;mySetup&lt;/span&gt;&lt;/code&gt; function:&lt;pre&gt;setupData = undefined;&lt;/pre&gt;Personally, though, I prefer modularity: Break out the bit that needs to deal with the big data set into its own function, and the setup of the event handlers in &lt;span style="font-style:italic;"&gt;their&lt;/span&gt; own function:&lt;pre&gt;function myBetterSetup()&lt;br /&gt;{&lt;br /&gt;    doTheBigDataThing();&lt;br /&gt;    setupEventHandlers();&lt;br /&gt;}&lt;br /&gt;function doTheBigDataThing()&lt;br /&gt;{&lt;br /&gt;    var setupData;&lt;br /&gt;    var n;&lt;br /&gt;&lt;br /&gt;    // Set 'setupData' to some large amount of data used only for setup;&lt;br /&gt;    // the below is just a contrived array.&lt;br /&gt;    setupData = [];&lt;br /&gt;    for (n = 0; n &lt; 1000; ++n)&lt;br /&gt;    {&lt;br /&gt;        setupData[n] = "Item " + n;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // (Presumably use the setup data for something here)&lt;br /&gt;}&lt;br /&gt;function setupEventHandlers()&lt;br /&gt;{&lt;br /&gt;    Event.observe(&lt;br /&gt;        'someButton',&lt;br /&gt;        'click',&lt;br /&gt;        function()&lt;br /&gt;        {&lt;br /&gt;            // Do something interesting&lt;br /&gt;        }&lt;br /&gt;    );&lt;br /&gt;    Event.observe(&lt;br /&gt;        'someOtherButton',&lt;br /&gt;        'click',&lt;br /&gt;        function()&lt;br /&gt;        {&lt;br /&gt;            // Do something else interesting&lt;br /&gt;        }&lt;br /&gt;    );&lt;br /&gt;    // (Etc.)&lt;br /&gt;}&lt;/pre&gt;This give us a clear separation of what we're doing, and as a nice side-effect, prevents the closures from keeping our data set around unnecessarily.&lt;br /&gt;&lt;br /&gt;At this point, a couple of you might be thinking "OMG! But that means any time I'm dealing with a big temporary data set, I need to be sure no closures are defined within that context! What if I want to act on the data set with an iteration function like in Example #5?!" Don't worry. Remember that the context is kept around because it has a reference from the closure; when the closure is released and cleaned up by the garbage collector, the context is also released and can be cleaned up by the GC. This only matters if you're keeping an enduring reference to the closure, as in the case of event handlers.&lt;br /&gt;&lt;br /&gt;&lt;a name='yours'&gt;&lt;/a&gt;&lt;span style="font-weight:bold;"&gt;#7 and on: Your Examples!&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;I've tried to give some overview of closures based on examples of usage, and I hope it's been useful, but I've really only scratched the surface here; what are &lt;span style="font-weight:bold;"&gt;your&lt;/span&gt; examples? Post away!&lt;script type='text/javascript'&gt;var onloadFunctions = []; var Event = {}; Event.observe = function(element, eventName, handler) { if (typeof element == "string") { element = document.getElementById(element); } if (element.addEventListener) { element.addEventListener(eventName, handler, false); } else { element.attachEvent('on' + eventName, handler); } }; function init() { var f; while (f = onloadFunctions.pop()) { f(); } }; function wireUpMessage(element, msg) { Event.observe( element, 'click', function() { alert(msg); } ); }; onloadFunctions.push(function() { wireUpMessage('btnSayHey', 'Hey there'); }); function setupCounterButtons(startBtnName, showBtnName, stopBtnName) { var counter; var intid; counter = 0; intid = undefined; function startCounter() { stopCounter(); counter = 0; intid = window.setInterval(function() { ++counter; }, 200); } function stopCounter() { if (intid !== undefined) { window.clearInterval(intid); intid = undefined; } } function showCounter() { var msg; msg = "Counter = " + counter + " ("; if (intid === undefined) { msg += "not "; } msg += "running)"; alert(msg); } Event.observe( document.getElementById(startBtnName), 'click', startCounter ); Event.observe( document.getElementById(showBtnName), 'click', showCounter ); Event.observe( document.getElementById(stopBtnName), 'click', stopCounter ); } onloadFunctions.push(function() { setupCounterButtons('btnStartCounter1', 'btnShowCounter1', 'btnStopCounter1'); }); onloadFunctions.push(function() { setupCounterButtons('btnStartCounter2', 'btnShowCounter2', 'btnStopCounter2'); }); function Circle(radius) { this.setRadius = function(r) { if (r &lt; 0) { throw "Radius cannot be less than zero."; } radius = r; }; this.getRadius = function() { return radius; }; this.setRadius(radius); }; function testCircle1() { var c; c = new Circle(10); alert("Radius: " + c.radius); }; function testCircle2() { var c; c = new Circle(10); alert("Radius before update: " + c.getRadius()); c.setRadius(20); alert("Radius after update: " + c.getRadius()); }; onloadFunctions.push(function() { Event.observe('btnTestCircle1', 'click', testCircle1); }); onloadFunctions.push(function() { Event.observe('btnTestCircle2', 'click', testCircle2); }); window.setTimeout(init, 100);&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-2341573448995158355?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/KveYpv-nSjQ" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/KveYpv-nSjQ/closures-by-example.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">3</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/03/closures-by-example.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-3151804591489710788</guid><pubDate>Mon, 03 Mar 2008 13:00:00 +0000</pubDate><atom:updated>2008-03-17T11:57:09.857Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">JavaScript</category><category domain="http://www.blogger.com/atom/ns#">var</category><category domain="http://www.blogger.com/atom/ns#">pitfall</category><title>Poor misunderstood 'var'</title><description>It seems most programmers coming to JavaScript from C, C++, Java, and the like equate the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;var&lt;/span&gt;&lt;/code&gt; statement with variable declaration statements in the languages they come from and use it the same way. And at some casual level that's reasonable; but it can lead you down a misleading path...&lt;br /&gt;&lt;br /&gt;Consider this code:&lt;pre&gt;function foo()&lt;br /&gt;{&lt;br /&gt;    var ar;&lt;br /&gt;&lt;br /&gt;    // ...do some stuff, create an array in 'ar'...&lt;br /&gt;&lt;br /&gt;    for (var index = 0; index &lt; ar.length; ++index)&lt;br /&gt;    {&lt;br /&gt;        doSomethingWith(ar[index]);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;This is a common idiom, but a misleading one. You might think that &lt;code&gt;&lt;span style="font-weight:bold;"&gt;index&lt;/span&gt;&lt;/code&gt; is only defined within the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;for&lt;/span&gt;&lt;/code&gt; loop (that's certainly the impression we're giving in the code). But it's not true: In fact, &lt;code&gt;&lt;span style="font-weight:bold;"&gt;index&lt;/span&gt;&lt;/code&gt; is defined throughout the function&amp;nbsp;-- within the loop, outside the loop, above the loop, and below the loop. The &lt;code&gt;&lt;span style="font-weight:bold;"&gt;var&lt;/span&gt;&lt;/code&gt; statement defines a variable within the current scope (all of it, not just "from here on"), and unlike some other languages, in JavaScript blocks don't have any effect on scope; only functions introduce a new scope.&lt;br /&gt;&lt;br /&gt;Consequently, the above function can be written as it is above, but also with the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;index&lt;/span&gt;&lt;/code&gt; declaration...&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;...at the top:&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;function foo()&lt;br /&gt;{&lt;br /&gt;    var ar;&lt;br /&gt;    var index;&lt;br /&gt;&lt;br /&gt;    // ...do some stuff, create an array in 'ar'...&lt;br /&gt;&lt;br /&gt;    for (index = 0; index &lt; ar.length; ++index)&lt;br /&gt;    {&lt;br /&gt;        doSomethingWith(ar[index]);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;span style="font-weight:bold;"&gt;...at the bottom:&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;function foo()&lt;br /&gt;{&lt;br /&gt;    var ar;&lt;br /&gt;&lt;br /&gt;    // ...do some stuff, create an array in 'ar'...&lt;br /&gt;&lt;br /&gt;    for (index = 0; index &lt; ar.length; ++index)&lt;br /&gt;    {&lt;br /&gt;        doSomethingWith(ar[index]);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    var index;&lt;br /&gt;}&lt;/pre&gt;&lt;span style="font-weight:bold;"&gt;...anywhere in the middle:&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;function foo()&lt;br /&gt;{&lt;br /&gt;    var ar;&lt;br /&gt;&lt;br /&gt;    // ...do some stuff, create an array in 'ar'...&lt;br /&gt;&lt;br /&gt;    for (index = 0; index &lt; ar.length; ++index)&lt;br /&gt;    {&lt;br /&gt;        var index;&lt;br /&gt;        doSomethingWith(ar[index]);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;span style="font-weight:bold;"&gt;...or even all of them!&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;function foo()&lt;br /&gt;{&lt;br /&gt;    var ar;&lt;br /&gt;    var index;&lt;br /&gt;&lt;br /&gt;    // ...do some stuff, create an array in 'ar'...&lt;br /&gt;&lt;br /&gt;    for (var index = 0; index &lt; ar.length; ++index)&lt;br /&gt;    {&lt;br /&gt;        doSomethingWith(ar[index]);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    var index;&lt;br /&gt;}&lt;/pre&gt;We can get away with that last one because a &lt;code&gt;&lt;span style="font-weight:bold;"&gt;var&lt;/span&gt;&lt;/code&gt; statement defining a variable that already exists in the current scope does not replace the variable (this is what keeps you from accidentally masking your function's arguments, or even the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;arguments&lt;/span&gt;&lt;/code&gt; array that's provided for you).&lt;br /&gt;&lt;br /&gt;This seems like an odd way to define the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;var&lt;/span&gt;&lt;/code&gt; statement until you get into the plumbing of JavaScript and how it sets up calls to functions. You can get into some of that by reading my earlier post, &lt;a href="/2008/02/closures-are-not-complicated.html"&gt;Closures are not complicated&lt;/a&gt;, but the net effect of the plumbing is that all &lt;code&gt;&lt;span style="font-weight:bold;"&gt;var&lt;/span&gt;&lt;/code&gt; statements are treated as though they were at the top of the function (if they have initializers, those become assignments and stay where they are).&lt;br /&gt;&lt;br /&gt;So does that mean that the common idiom of declaring an indexer within the loop statement is "wrong"? Well, that's a matter of perspective, and &lt;s&gt;the older I get&lt;/s&gt; the more experience I accumulate, the less I think in terms of absolutes like right and wrong. The language spec allows it, so in that sense it's not "wrong". In some ways, it's sort of a shorthand way of telling the next person reading the code that you're going to use it for the loop (and only for the loop, right?), so in that sense perhaps it's not "wrong".&lt;br /&gt;&lt;br /&gt;But the further your code gets from expressing what's really happening, the easier it is for someone reading the code later (perhaps you!) to get the wrong end of the stick and introduce a problem. For example, suppose you have a 30-some-odd-line function and the loop appears in within the body of a conditional about two-thirds of the way down:&lt;pre&gt;function foo(someArray)&lt;br /&gt;{&lt;br /&gt;    var thingy;&lt;br /&gt;    var otherThingy;&lt;br /&gt;&lt;br /&gt;    // ...20 lines of code...&lt;br /&gt;&lt;br /&gt;    if (thingy &gt; otherThingy)&lt;br /&gt;    {&lt;br /&gt;        for (var index = 0; index &lt; someArray.length; ++index)&lt;br /&gt;        {&lt;br /&gt;            doSomethingWith(someArray[index]);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // ...10 more lines of code...&lt;br /&gt;}&lt;/pre&gt;Six months after you write this, Mike edits the function and needs to remember the index of something at the top so he can do something with it at the bottom; he declares an "index" variable, sets &lt;code&gt;&lt;span style="font-weight:bold;"&gt;index&lt;/span&gt;&lt;/code&gt; at the top, and then uses it at the bottom, having missed the loop:&lt;pre&gt;function foo(someArray)&lt;br /&gt;{&lt;br /&gt;    var thingy;&lt;br /&gt;    var otherThingy;&lt;br /&gt;    &lt;span style="font-weight:bold;"&gt;var index;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;    &lt;span style="font-weight:bold;"&gt;index = findSomething(someArray);&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;    // ...20 lines of code...&lt;br /&gt;&lt;br /&gt;    if (thingy &gt; otherThingy)&lt;br /&gt;    {&lt;br /&gt;        for (var index = 0; index &lt; someArray.length; ++index)&lt;br /&gt;        {&lt;br /&gt;            doSomethingWith(someArray[index]);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // ...10 more lines of code...&lt;br /&gt;&lt;br /&gt;    &lt;span style="font-weight:bold;"&gt;restoreSomething(someArray, index);&lt;/span&gt;&lt;br /&gt;}&lt;/pre&gt;Mike's introduced a bug, an irritating, intermittent bug. Sometimes the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;restoreSomething&lt;/span&gt;&lt;/code&gt; call at the end fails for some reason; not always, mind, but sometimes. (Because &lt;code&gt;&lt;span style="font-weight:bold;"&gt;index&lt;/span&gt;&lt;/code&gt; gets set by the loop, but only when &lt;code&gt;&lt;span style="font-weight:bold;"&gt;thingy&amp;nbsp;&amp;gt;&amp;nbsp;otherThingy&lt;/span&gt;&lt;/code&gt;.)&lt;br /&gt;&lt;br /&gt;Obviously, this bug could have been avoided if Mike had read through the entire function carefully before making his mods. Or if you'd chosen a different name for your index variable (in hopes of reducing the odds of Mike using it). Or it could have been caught by thorough unit tests that explore all conditions (and then Mike would have to go back and fix it).&lt;br /&gt;&lt;br /&gt;But let's throw Mike a bone, eh? If we declare the variable in the text in the same place it's defined by the interpreter at runtime, we help him avoid making the mistake in the first place. And we like Mike, we don't want to trip him up...right?&lt;br /&gt;&lt;br /&gt;Regardless of your decision about how to write your code, though, understanding what &lt;code&gt;&lt;span style="font-weight:bold;"&gt;var&lt;/span&gt;&lt;/code&gt; is really doing can help you get that code doing what you want it to do.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-3151804591489710788?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/Hyts8cm119I" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/Hyts8cm119I/poor-misunderstood-var.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/03/poor-misunderstood-var.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-2553763848169256182</guid><pubDate>Fri, 29 Feb 2008 21:00:00 +0000</pubDate><atom:updated>2008-03-03T13:09:57.159Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">JavaScript</category><category domain="http://www.blogger.com/atom/ns#">closures</category><category domain="http://www.blogger.com/atom/ns#">scope</category><title>Closures are not complicated</title><description>Closures seem to frighten people a bit. Partially I suspect this is down to the academic nature of the term "closure". It sounds like something Californians look to achieve, not something to help you write software. &lt;span style="font-style: italic;"&gt;(Disclosure: I mostly grew up in San Francisco, so I'm allowed to poke fun at my fellow Californians. Don't Try This At Home.)&lt;/span&gt; I suspect it's also because if you don't know the rules for them, they seem mysterious, and the mysterious is often frightening.&lt;br /&gt;&lt;br /&gt;First off, what is a closure? I'll leave a thorough definition to my academic betters, but let's put it this way for my fellow plodders and I:  A closure is a function with data intrinsically bound to it.&lt;br /&gt;&lt;br /&gt;Consider this code:&lt;pre&gt;function updateDisplay(panel, contentId)&lt;br /&gt;{&lt;br /&gt;    var url;&lt;br /&gt;&lt;br /&gt;    url = 'getcontent?id=' + contentId;&lt;br /&gt;    jsonRequest(&lt;br /&gt;        url,&lt;br /&gt;        function(resp)&lt;br /&gt;        {&lt;br /&gt;            if (resp.err)&lt;br /&gt;            {&lt;br /&gt;                panel.addClassName('error');&lt;br /&gt;                panel.update(&lt;br /&gt;                    'Error retrieving content ID '&lt;br /&gt;                    + contentId&lt;br /&gt;                    + ' from "'&lt;br /&gt;                    + url&lt;br /&gt;                    + '", error: '&lt;br /&gt;                    + resp.err);&lt;br /&gt;            }&lt;br /&gt;            else&lt;br /&gt;            {&lt;br /&gt;                panel.removeClassName('error');&lt;br /&gt;                panel.update(resp.json.content);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    );&lt;br /&gt;}&lt;/pre&gt;This updates a panel element based on the results of a call to retrieve some &lt;a href="http://en.wikipedia.org/wiki/JSON"&gt;JSON&lt;/a&gt; data. The call to the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;jsonRequest&lt;/span&gt;&lt;/code&gt; function accepts two parameters: The URL that will return the JSON data, and a callback function to trigger when the request completes (one way or the other). If the data was returned successfully, the callback sets the content of the panel from the JSON data and makes sure that the "error" CSS class is not set on the element; if there's an error, it shows details about the error and sets the "error" CSS class. (In this example, we happen to be using &lt;a href="http://www.prototypejs.org/"&gt;Prototype&lt;/a&gt; to extend our panel element with the nifty class name and update methods, but that's as much to keep the example simple as anything else.)&lt;br /&gt;&lt;br /&gt;The callback above is an example of a closure: A function with data bound to it, in this case the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;panel&lt;/span&gt;&lt;/code&gt; and &lt;code&gt;&lt;span style="font-weight:bold;"&gt;contentId&lt;/span&gt;&lt;/code&gt; arguments we passed into the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;updateDisplay&lt;/span&gt;&lt;/code&gt; function, and also &lt;code&gt;&lt;span style="font-weight:bold;"&gt;updateDisplay&lt;/span&gt;&lt;/code&gt;'s &lt;code&gt;&lt;span style="font-weight:bold;"&gt;url&lt;/span&gt;&lt;/code&gt; local variable. It's useful to have this information bound to the callback, because the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;jsonRequest&lt;/span&gt;&lt;/code&gt; function doesn't know anything about &lt;code&gt;&lt;span style="font-weight:bold;"&gt;panel&lt;/span&gt;&lt;/code&gt; or &lt;code&gt;&lt;span style="font-weight:bold;"&gt;contentId&lt;/span&gt;&lt;/code&gt;, it just knows about triggering the callback&amp;nbsp;-- but the callback has the information it needs to do its job.&lt;br /&gt;&lt;br /&gt;Magic? Nah. I can't speak for closures in other languages, but there's nothing complicated about closures in JavaScript. Seriously. They're dead easy. You need to know, say, three things and you're good to go. Well, four things, but that's only because someone has been misinforming you. Here's a quick list of those four things, after which we'll delve in a bit deeper, and then I'll tell you something at the end that will surprise you for three seconds before you go "Oh, of course":&lt;br /&gt;&lt;ol&gt;&lt;li&gt;In JavaScript, &lt;span style="font-weight: bold;"&gt;everything&lt;/span&gt; is a data structure, even functions, and -- critically -- even the context in which functions run. One aspect of that context is a "call object" (that's &lt;span style="text-decoration: underline;"&gt;&lt;/span&gt;&lt;a href="http://www.oreilly.com/catalog/jscript5/"&gt;Flanagan&lt;/a&gt;'s term, the &lt;a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm"&gt;ECMA specification&lt;/a&gt; uses "activation object" -- I'll use "call object" because &lt;s&gt;I'm lazy and it's less typing&lt;/s&gt; I find it clearer).&lt;/li&gt;&lt;li&gt;JavaScript variable names are resolved on the basis of a "scope chain", which includes (among other things) the globlal object and all of the current call objects in scope.&lt;/li&gt;&lt;li&gt;Functions in JavaScript are lexically scoped -- for the plodders like me out there, that means that the things a function can access (the things "in scope" for it) are determined by the context in which the function is &lt;span style="font-style: italic;"&gt;defined&lt;/span&gt;, not the context in which it's executed.&lt;/li&gt;&lt;li&gt;Closures do not create memory leaks. Someone probably told you that they did at some point (perhaps they thought that's what Microsoft was trying to say &lt;a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/IETechCol/dnwebgen/ie_leak_patterns.asp"&gt;here&lt;/a&gt;).&lt;/li&gt;&lt;/ol&gt;Okay, let's see how those things come together to make closures easy.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;#1: Everything is a data structure&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;When we call a JavaScript function, the context of that call to the function -- the parameters we've used, the variables within the function itself -- are part of a data structure called the call object (or, again, "activation object" in ECMA parlance). The interpreter creates a call object for this particular execution of the function and sets some properties on that call object before passing it into the function's code. The properties are:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;A property called &lt;code&gt;&lt;span style="font-weight: bold;"&gt;arguments&lt;/span&gt;&lt;/code&gt; which is an array (of sorts, in most implementations it's not actually an Array object) of the actual arguments we called the function with, plus a &lt;code&gt;&lt;span style="font-weight: bold;"&gt;callee&lt;/span&gt;&lt;/code&gt; property which is a reference to the function being called.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;A property for each of the arguments defined by the function declaration. The values of these properties are set to the values passed into the function. If any arguments weren't specified (because JavaScript lets you call functions with however many arguments you want, regardless of the definition), properties for any missing arguments are still created on the call object -- with the value &lt;code&gt;&lt;span style="font-weight: bold;"&gt;undefined&lt;/span&gt;&lt;/code&gt;.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;A property for every declared variable within the function (e.g., every "var" statement). (These start out with the value &lt;code&gt;&lt;span style="font-weight: bold;"&gt;undefined&lt;/span&gt;&lt;/code&gt;.)&lt;br /&gt;&lt;/li&gt;&lt;/ol&gt;Let's look again at selected bits of the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;updateDisplay&lt;/span&gt;&lt;/code&gt; function from earlier:&lt;pre&gt;function updateDisplay(panel, contentId)&lt;br /&gt;{&lt;br /&gt;    var url;&lt;br /&gt;&lt;br /&gt;    // ...&lt;br /&gt;}&lt;/pre&gt;And let's assume we call it with a reference to a 'leftPanel' div and a contentId of 123:&lt;pre&gt;updateDisplay(leftPanel, 123);&lt;/pre&gt;That creates a call object for this execution of &lt;code&gt;&lt;span style="font-weight:bold;"&gt;updateDisplay&lt;/span&gt;&lt;/code&gt; that essentially looks like this:&lt;pre&gt;call.arguments = [leftPanel, 123]&lt;br /&gt;call.arguments.callee = updateDisplay&lt;br /&gt;call.panel = leftPanel&lt;br /&gt;call.contentId = 123&lt;br /&gt;call.url = undefined&lt;/pre&gt;This object is then used within the body of the function when the code uses the arguments &lt;code&gt;&lt;span style="font-weight:bold;"&gt;panel&lt;/span&gt;&lt;/code&gt; or &lt;code&gt;&lt;span style="font-weight: bold;"&gt;contentId&lt;/span&gt;&lt;/code&gt;, or the local variable &lt;code&gt;&lt;span style="font-weight: bold;"&gt;url&lt;/span&gt;&lt;/code&gt;, etc.&lt;br /&gt;&lt;br /&gt;"But wait," you say. "I don't refer to an object when I use the arguments or variables in my function, I just use their names." Indeed&amp;nbsp;-- the use of the call object is &lt;span style="font-style: italic;"&gt;implicit&lt;/span&gt;. How do we end up using the call object when we just write "contentId" (for instance)? Because once the call object is created, it's put at the top of the &lt;span style="font-style:italic;"&gt;scope chain&lt;/span&gt; for the duration of the function call. Which takes us nicely to...&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;#2: Variable names are resolved using a "scope chain"&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;If you've written JavaScript in a browser environment, you've probably used the global &lt;code&gt;&lt;span style="font-weight: bold;"&gt;document&lt;/span&gt;&lt;/code&gt; object, and perhaps the global &lt;code&gt;&lt;span style="font-weight: bold;"&gt;navigator&lt;/span&gt;&lt;/code&gt; object as well. Here's the thing: Those aren't global objects. Those are &lt;span style="font-style: italic;"&gt;properties&lt;/span&gt; of a global object -- in fact, of &lt;span style="font-style: italic;"&gt;the&lt;/span&gt; global object. The &lt;code&gt;&lt;span style="font-weight: bold;"&gt;document&lt;/span&gt;&lt;/code&gt; and &lt;code&gt;&lt;span style="font-weight: bold;"&gt;navigator&lt;/span&gt;&lt;/code&gt; properties are set up for you by the browser, but they're just properties of an object.&lt;br /&gt;&lt;br /&gt;So how do you get away with just giving the property name, rather than giving the object name as well?  Because of the &lt;span style="font-weight: bold; font-style: italic;"&gt;scope chain&lt;/span&gt;, an ordered series (indeed, a chain) of objects. When the JavaScript interpreter sees an unqualified variable reference, it checks the top object on the scope chain to see if it has a property by that name: If so, it gets used; if not, the interpreter checks the next object down the chain. The global object is the bottom of the chain, so if you just type &lt;code&gt;&lt;span style="font-weight: bold;"&gt;document.writeln("Blah blah blah")&lt;/span&gt;&lt;/code&gt;, eventually the &lt;code&gt;&lt;span style="font-weight: bold;"&gt;document&lt;/span&gt;&lt;/code&gt; property is found on the global object and used.&lt;br /&gt;&lt;br /&gt;(The global object is an abstract entity in the generic JavaScript definition, but in the specific case of a web browser you know it by another name:  &lt;code&gt;&lt;span style="font-weight: bold;"&gt;window&lt;/span&gt;&lt;/code&gt;. In browsers, the &lt;code&gt;&lt;span style="font-weight: bold;"&gt;window&lt;/span&gt;&lt;/code&gt; object &lt;span style="font-style: italic;"&gt;is&lt;/span&gt; the global object; it just also has a property, "&lt;code&gt;&lt;span style="font-weight: bold;"&gt;window&lt;/span&gt;&lt;/code&gt;", that refers to itself.)&lt;br /&gt;&lt;br /&gt;So quick:  Within a function, how do variable names get resolved?  &lt;span style="font-weight: bold; font-style: italic;"&gt;Right!&lt;/span&gt;  When the function is being executed, the call object with all those nifty properties for the function's arguments and variables is put at the top of the scope chain. So during our call to &lt;code&gt;&lt;span style="font-weight:bold;"&gt;updateDisplay&lt;/span&gt;&lt;/code&gt; from earlier, the call object for the call is at the top of the scope chain, followed by the global object, like this:&lt;br /&gt;&lt;br /&gt;&lt;img src='http://www.crowdersoftware.com/bimg/chain1.png' /&gt;&lt;br /&gt;&lt;br /&gt;When the interpreter sees a variable reference, say &lt;code&gt;&lt;span style="font-weight: bold;"&gt;contentId&lt;/span&gt;&lt;/code&gt;, it looks on the call object: If there's a &lt;code&gt;&lt;span style="font-weight: bold;"&gt;contentId&lt;/span&gt;&lt;/code&gt; property on the call object, it gets used; otherwise, the interpreter looks at the next object in the scope chain, which in this case is the global object.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style:italic;"&gt;(There's more to know about the scope chain than I've described here; the astute reader will be wondering, for instance, how objects and their instance members come into play, or what the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;with&lt;/span&gt;&lt;/code&gt; statement does to things. Alas, we can't tackle everything all at once...)&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;But how can I know when I'm writing &lt;code&gt;&lt;span style="font-weight:bold;"&gt;updateDisplay&lt;/span&gt;&lt;/code&gt; that the scope chain will look like that? I mean, doesn't it depend on who's calling the function? Nope. And that brings us to our next point:&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;#3: Functions in JavaScript are lexically scoped&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Okay, so we get the concept of the call object, which is created when we call a function; and we get the global object, which sits at the bottom of the scope chain to handle globals. But what's this "lexically scoped" thing? It's just a fancy way of saying that a function's scope is determined by where it's defined (e.g., the text defining it; &lt;span style="font-style:italic;"&gt;l&amp;eacute;xis&lt;/span&gt; is Greek for "word" or "speech"), not where it's called.&lt;br /&gt;&lt;br /&gt;Let's put that another way: When a function is defined, the code defining it is in some kind of context&amp;nbsp;-- a function is running, or the page itself is running if you've done the code at the top level. That context has an active scope chain when the function is defined. So when creating the function object, the interpreter creates a property on it (called [[Scope]] in the ECMA spec, but you can't access it directly) with a reference to the active execution context's scope chain. Even when the context goes away (e.g., the function returns), because the function object created by the definition has a reference to the scope chain, the scope chain isn't garbage collected&amp;nbsp;-- it's kept alive by the active reference to it from our function object. (Assuming that we've kept a reference to the function object, as we did in our example by passing it into the &lt;code&gt;&lt;span style="font-weight:bold;"&gt;jsonRequest&lt;/span&gt;&lt;/code&gt; method; otherwise, the function and the scope chain are both garbage-collected since nothing references them.)&lt;br /&gt;&lt;br /&gt;Remember our closure at the beginning of this post? It gets a [[Scope]] property pointing to the scope chain in effect when &lt;code&gt;&lt;span style="font-weight:bold;"&gt;updateDisplay&lt;/span&gt;&lt;/code&gt; was called with &lt;code&gt;&lt;span style="font-weight:bold;"&gt;panel&lt;/span&gt;&lt;/code&gt; = &lt;code&gt;&lt;span style="font-weight:bold;"&gt;leftPanel&lt;/span&gt;&lt;/code&gt;, etc.:&lt;br /&gt;&lt;br /&gt;&lt;img src='http://www.crowdersoftware.com/bimg/closureobject.png'&gt;&lt;br /&gt;&lt;br /&gt;So when we call it, first its scope chain is put in place, then the call object for this particular call to the function is put on top of the scope chain, and the function is executed with this chain:&lt;br /&gt;&lt;br /&gt;&lt;img src='http://www.crowdersoftware.com/bimg/chain2.png'&gt;&lt;br /&gt;&lt;br /&gt;And there we are, the closure can access &lt;code&gt;&lt;span style="font-weight:bold;"&gt;panel&lt;/span&gt;&lt;/code&gt; and all of the other properties of the call object for the call to &lt;code&gt;&lt;span style="font-weight:bold;"&gt;updateDisplay&lt;/span&gt;&lt;/code&gt; because they're on the scope chain. They're on the scope chain because that was stuck onto the closure's function object when it was created. No magic. Just data structures, the scope chain, and lexical scoping all working together.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;#4: Closures don't cause memory leaks&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;So why do people think closures cause memory leaks? A couple of reasons, I suspect, but chief among them being &lt;s&gt;a bug in&lt;/s&gt; an &lt;span style="font-style:italic;"&gt;issue&lt;/span&gt; with Internet Explorer. IE's DOM objects are not garbage-collected in the same way that JavaScript objects are; instead, IE shows its &lt;a href="http://en.wikipedia.org/wiki/Component_Object_Model"&gt;COM&lt;/a&gt; roots by using reference counting, a mechanism that is, unfortunately, prey to issues with circular references. Event handlers can easily end up being circular references, and so in IE it's easy to "leak" the memory associated with a DOM element and its event handler because they're referring to each other. (JavaScript's garbage collector doesn't have an issue with circular references; it works on the  "reachability" principle rather than reference counting.) This is an issue with event handlers, rather than closures, but since many event handlers are written as closures, people associate it with closures. Fortunately, it's not that hard to kick IE into shape (in this particular way); Crockford talks about the problem and its solution &lt;a href="http://javascript.crockford.com/memory/leak.html"&gt;here&lt;/a&gt; and many toolkits [like Prototype] will do this for you if you ask them nicely.&lt;br /&gt;&lt;br /&gt;Lest I be accused of Microsoft-bashing, I should point out that IE is not the only browser that sometimes loses track of things; it's just by far the worst. Firefox 2 has a bad habit of leaking a bit of memory on XmlHTTPRequest calls, which also frequently involve closures. The good news there is that &lt;a href="http://developer.mozilla.org/en/docs/Firefox_3_for_developers"&gt;Firefox 3 beta 3&lt;/a&gt; is looking awfully good indeed on this front.&lt;br /&gt;&lt;br /&gt;Separate from browser issues, though, if you're not really clear on how closures work, particularly with regard to the scope chain, you'll miss the fact that a closure keeps a reference to &lt;span style="font-weight:bold;"&gt;all&lt;/span&gt; of the variables and arguments in scope where it's created, not just the ones it uses; and so if you have (say) a massive temporary array allocated in that scope that the closure doesn't use, you might be tempted to say that the closure is causing the array's memory to leak. (The answer there is simple: Clear the array's variable when you're done with it.)&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;In Conclusion&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;There are lots of nifty things you can do with closures. I'll post a follow-up in a couple of days, "Closures By Example", demonstrating a few of them and just generally walking through some &lt;span style="font-style:italic;"&gt;seemingly&lt;/span&gt;-complicated examples.  But until then, I'll just reiterate my theme: Closures in JavaScript are not complicated. They're powerful, but if you understand that 1.&amp;nbsp;Everything is a data structure, 2.&amp;nbsp;Variables&amp;nbsp;-- I should probably call them unqualified references&amp;nbsp;-- are resolved according to a scope chain, and 3.&amp;nbsp;The scope chain for a function is defined by where the function is defined &lt;span style="font-style:italic;"&gt;lexically&lt;/span&gt;, you'll be golden.&lt;br /&gt;&lt;br /&gt;Oh! I said I'd tell you something at the end that would surprise you for about three seconds before you said "Oh, of course." Here it is:&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style:italic;"&gt;All JavaScript functions are closures.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Happy coding!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-2553763848169256182?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/uxW_83iX3u8" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/uxW_83iX3u8/closures-are-not-complicated.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">3</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-5776624389634991887</guid><pubDate>Mon, 18 Feb 2008 17:30:00 +0000</pubDate><atom:updated>2008-03-16T00:51:39.646Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">operator</category><category domain="http://www.blogger.com/atom/ns#">JavaScript</category><title>JavaScript's Curiously-Powerful OR Operator (||)</title><description>The "or" operator (&lt;code&gt;||&lt;/code&gt;). It seems innocuous enough:  A binary logical operator that returns true if either of its params is true, usually used in the context of a conditional statement:&lt;pre&gt;    if (a || b)&lt;/pre&gt;Perhaps if you've been programming in any of several other high-level languages for a while, you expect that it won't evaluate the second param if the first one is true, something called short-circuiting. And you'd be right. But there's a lot more to the JavaScript &lt;code&gt;||&lt;/code&gt; operator than that!&lt;br /&gt;&lt;br /&gt;Consider this statement: &lt;pre&gt;    x = a || b;&lt;/pre&gt;If the &lt;code&gt;||&lt;/code&gt; operator were purely a logical operator, then &lt;code&gt;x&lt;/code&gt; would receive one of two values: &lt;code&gt;true&lt;/code&gt; or &lt;code&gt;false&lt;/code&gt;. But that's not what happens. Instead, &lt;code&gt;x&lt;/code&gt; gets the value of &lt;code&gt;a&lt;/code&gt; if &lt;code&gt;a&lt;/code&gt; is true or can be converted to being "true", otherwise it gets the value of &lt;code&gt;b&lt;/code&gt;. And that's another kettle of fish entirely.&lt;br /&gt;&lt;br /&gt;First off, there's this question of "...or can be converted to being "true"..."  What is truth? &lt;span style="font-style: italic;"&gt;(And whither beauty?  Never mind, that's a different blog...)&lt;/span&gt; I won't go into the ins and outs of JavaScript's type coercion here (refer to Flanagan's book), but for our purposes today, &lt;code&gt;a&lt;/code&gt; can be converted to "true" if it's &lt;span style="font-style: italic;"&gt;not&lt;/span&gt; zero, an empty string, null, or undefined.  So 1 is considered true, as is the string "Fred", as is an object reference.&lt;br /&gt;&lt;br /&gt;But lots of languages do at least some level of type coercion; what marks the JavaScript operator out as special is the result of the expression: What you get back isn't a &lt;code&gt;true&lt;/code&gt; or &lt;code&gt;false&lt;/code&gt;, but rather the &lt;span style="font-style: italic;"&gt;value&lt;/span&gt; of one of the operator's parameters.  Now that's interesting, and it's something you may not be expecting if you're relatively new to the language. It can make it difficult for a newcomer to read some of the more dense JavaScript found in sample code, toolkits, etc.&lt;br /&gt;&lt;br /&gt;Here's an example I ran across a few weeks back (the names have been changed for simplicity):&lt;pre&gt;    function sort(comparator)&lt;br /&gt;    {&lt;br /&gt;        comparator = comparator || this.defaultComparator;&lt;br /&gt;        // ...&lt;br /&gt;    }&lt;/pre&gt;Here, the author provides a &lt;code&gt;sort&lt;/code&gt; method which takes an optional &lt;code&gt;comparator&lt;/code&gt; function reference; if you don't supply one, the class's default comparator is used instead. Let's break that down a bit in each scenario.&lt;br /&gt;&lt;br /&gt;If you call the method without supplying a comparator function reference:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;&lt;code&gt;comparator&lt;/code&gt; is undefined.&lt;/li&gt;&lt;li&gt;The expression evaluates &lt;code&gt;comparator&lt;/code&gt;, sees the undefined value, and converts it to a boolean: false.&lt;/li&gt;&lt;li&gt;Because the first parameter is false, the operator returns the second parameter's value.&lt;/li&gt;&lt;/ol&gt;And now let's look at it if you &lt;span style="font-weight: bold;"&gt;do&lt;/span&gt; supply a comparator function reference:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;&lt;code&gt;comparator&lt;/code&gt; is a reference to a function.&lt;/li&gt;&lt;li&gt;The expression evaluates &lt;code&gt;comparator&lt;/code&gt;, sees the function reference, and converts it to a boolean: true.&lt;/li&gt;&lt;li&gt;Because the first parameter is true, the operator returns the first parameter's value (it never evaluates the second parameter at all).&lt;/li&gt;&lt;/ol&gt;So the author's line&lt;pre&gt;    comparator = comparator || this.defaultComparator;&lt;/pre&gt;sets up the &lt;code&gt;comparator&lt;/code&gt; variable with the default if it didn't already have a value.&lt;br /&gt;&lt;br /&gt;You might be asking, why not just do this:&lt;pre&gt;    if (!comparator)&lt;br /&gt;    {&lt;br /&gt;        comparator = this.defaultComparator;&lt;br /&gt;    }&lt;/pre&gt;Well, for one thing, it doesn't demonstrate l33t skilz, which is just as important to the current set of twentysomething coders as it was to the previous set, and the set before that (&lt;span style="font-style: italic;"&gt;as it is now, has it ever been&lt;/span&gt;). But they would probably also point out that even after being &lt;a href="http://javascript.crockford.com/jsmin.html"&gt;minified&lt;/a&gt;, the result is in the region of six characters longer -- or nearly 12% of the total. (And they both beat out the version using the &lt;a href='http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Operators:Special_Operators:Conditional_Operator'&gt;ternary&lt;/a&gt; operator.) Size counts with downloaded JavaScript. Some would also probably argue that it's more "expressive". Plodders like myself might raise counter-arguments about clarity, but that's the thing, to a day-in, day-out JavaScript coder, the statement isn't unclear.&lt;br /&gt;&lt;br /&gt;Let's take our example one step further: Suppose our hypothetical class with the &lt;code&gt;sort&lt;/code&gt; method only sets its &lt;code&gt;defaultComparator&lt;/code&gt; on the instance if it's explicitly set, and relies on a class-wide default otherwise? The &lt;code&gt;||&lt;/code&gt; operator lets us write the choice of the comparator function with a single line (split into three lines here for word-wrap):&lt;pre&gt;    comparator = comparator&lt;br /&gt;              || this.defaultComparator&lt;br /&gt;              || NiftyClass.classComparator;&lt;/pre&gt;The first &lt;code&gt;||&lt;/code&gt; tests &lt;code&gt;comparator&lt;/code&gt; and, finding it false-ish, takes the value of &lt;code&gt;this.defaultComparator&lt;/code&gt;; then the second &lt;code&gt;||&lt;/code&gt; evaluates &lt;code&gt;this.defaultComparator&lt;/code&gt; and, finding it false-ish, takes the value of &lt;code&gt;NiftyClass.classComparator&lt;/code&gt;. Putting it more simply: It selects the first one that's defined. As a &lt;a href='http://jockmurphy.com'&gt;good friend of mine&lt;/a&gt; said "...it is kind of a selection operator more than a logical one..." Indeed, it's almost a specialized version of the ternary operator where the test is for "truth" or "existence" (and I figure that's got to account for 80% or more of the use of the ternary operator).&lt;br /&gt;&lt;br /&gt;So, do we all want to see the &lt;code&gt;||&lt;/code&gt; idiom for selection rather than &lt;code&gt;if&lt;/code&gt; statements? There we enter the realm of style, I tend to doubt that either way is &lt;span style="font-style:italic;"&gt;markedly&lt;/span&gt; better than the other in terms of execution speed (which probably varies from engine to engine anyway), the size difference is minimal, and it's personal choice which is more expressive. But if you're going to be reading any significant amount of modern JavaScript, you'll see this&lt;pre&gt;    x = a || b || c;&lt;/pre&gt;idiom a lot, so be prepared for it. And if you're an old plodder like me, well...it does kinda grow on you. ;-)&lt;br /&gt;&lt;br /&gt;[I should point out that in early versions of JavaScript, the &lt;code&gt;||&lt;/code&gt; operator &lt;span style="font-weight:bold;"&gt;did&lt;/span&gt; evaluate to &lt;code&gt;true&lt;/code&gt; or &lt;code&gt;false&lt;/code&gt;, rather than providing this nifty return-the-value-of-the-param behavior. But the JavaScript engines in all major browsers (including IE6) use the behavior described above.]&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-5776624389634991887?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/LpyQcISGLaE" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/LpyQcISGLaE/javascripts-curiously-powerful-or.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/02/javascripts-curiously-powerful-or.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-542398624287876588.post-5295840437280908842</guid><pubDate>Thu, 14 Feb 2008 12:17:00 +0000</pubDate><atom:updated>2008-03-17T13:29:53.947Z</atom:updated><category domain="http://www.blogger.com/atom/ns#">JavaScript</category><category domain="http://www.blogger.com/atom/ns#">welcome</category><category domain="http://www.blogger.com/atom/ns#">meta</category><title>Nifty Snippets</title><description>Welcome to Nifty Snippets, my new blog for capturing little snippets of code and techniques (as well as engineering, business, and teamwork "lessons learned"). Initially the focus will be on Ajax stuff, and that means lots of JavaScript.&lt;br /&gt;&lt;br /&gt;Now, JavaScript is about 18 times more interesting than most people think. This is not a toy language, this is an incredibly rich, powerful, expressive language that until recently has been dramatically under-used. Partially that's because of how it was introduced to the world (scripting events in Netscape Navigator), and partially I suspect it's down to a bias many of us had toward hierarchical, class-based languages like Java and C++. JavaScript is neither hierarchical nor class-based; it's a prototype language.&lt;br /&gt;&lt;br /&gt;This first post is just meant to say "hi". (Hi!) But I'll also throw out a few handy links for those with an interest in JavaScript, Ajax, and rich web applications:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;If you're doing any serious work in JavaScript, read &lt;a href="http://javascript.crockford.com/"&gt;Crockford&lt;/a&gt;. If there's something powerful and interesting about the JavaScript language, the odds are Douglas Crockford has written about it in detail. Don't let the depth of the language daunt you, you can ease your way into it.&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Similarly, if you're doing Ajax apps, you need &lt;span style="font-style: italic;"&gt;JavaScript: The Definitive Guide&lt;/span&gt; by David Flanagan [&lt;a href="http://www.oreilly.com/catalog/jscript5/"&gt;O'Reilly&lt;/a&gt;, &lt;a href="http://www.amazon.com/dp/0596101996"&gt;Amazon&lt;/a&gt;].&lt;/li&gt;&lt;li&gt;Lots of people are really getting a lot out of &lt;a href="http://www.prototypejs.org/"&gt;Prototype&lt;/a&gt;, which is basically a bunch of nifty stuff for JavaScript wrapped up into a toolkit.&lt;/li&gt;&lt;li&gt;Many of those same people are enjoying the various effects and other goodness available via &lt;a href="http://script.aculo.us/"&gt;script.aculo.us&lt;/a&gt;.&lt;/li&gt;&lt;li&gt;Alternately, perhaps you'd like to peruse one of the dozens of other &lt;a href="http://www.google.com/search?q=javascript+toolkit"&gt;JavaScript toolkits&lt;/a&gt; out there.&lt;/li&gt;&lt;/ul&gt;Those'll get you started, anyway. Back soon with our first snippet!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/542398624287876588-5295840437280908842?l=blog.niftysnippets.org' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/NiftySnippets/~4/h7upbj8a0Tg" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/NiftySnippets/~3/h7upbj8a0Tg/nifty-snippets.html</link><author>noreply@blogger.com (T.J. Crowder)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><feedburner:origLink>http://blog.niftysnippets.org/2008/02/nifty-snippets.html</feedburner:origLink></item></channel></rss>
