<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <title>Posts about Javascript</title>
    <link>http://wiki.futuretoby.com/tag/javascript</link>
    <language>en-us</language>
    <item>
      <title>Node Knockout 2011 and Twends</title>
      <description>This past weekend I participated in the &amp;nbsp;&lt;a href="http://nodeknockout.com/"&gt;Node Knockout&lt;/a&gt;&amp;nbsp;- a programming competition where teams of 1 - 4 members build something using&amp;nbsp;&lt;a href="http://nodejs.org/"&gt;node.js&lt;/a&gt;&amp;nbsp;in 48 hours.&amp;nbsp;I was very fortunate to have worked with&amp;nbsp;&lt;a href="http://twitter.com/#!/robfaraj"&gt;@robfaraj&lt;/a&gt;&amp;nbsp;on this, it was a fun couple of days! The end result is what we call&amp;nbsp;&lt;s&gt;&lt;a href="http://cubespace.nko2.nodeknockout.com/"&gt;Twends&lt;/a&gt;&lt;/s&gt;&amp;nbsp;Twends: new location is now&amp;nbsp;&lt;a href="http://twends.us"&gt;twends.us&lt;/a&gt;. Twends is a real-time Twitter trend visualization...app. It looks like this&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;img title="Twends" alt="Twends" src="https://lh4.googleusercontent.com/-FYvHuvGFjdM/TlxSDd765JI/AAAAAAAAR00/mZeQg0h5R9o/s800/twends.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;First, you either select a trending topic or type in a term of your own, then you will see this word visualization based on a series of packed circles. The larger the circle and the redder it is, the more frequently the word is being said at the moment. All the while, birds are fly across the screen. Each bird on the screen represents a tweet that's been written, now...ish. Just sit back, relax and watch the pretty circles changing shape and the birds flying across your screen. By reading the words you can often learn interesting things. For example, I learned while reading Twends that Justin Beiber fans are called beliebers, while Taylor Swift fans are called swifies.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Oh! And here's a video of it in action&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;iframe src="http://www.screenr.com/embed/pSWs" width="650" height="396" frameborder="0"&gt;&lt;/iframe&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;The Tech&lt;/h2&gt;&lt;div&gt;Twends was built using client-side Javascript with the help of some great libraries and the&amp;nbsp;&lt;a href="https://dev.twitter.com/docs/api"&gt;Twitter REST API&lt;/a&gt;.&amp;nbsp;&lt;a href="http://mbostock.github.com/d3/" style="color: rgb(136, 136, 136); "&gt;d3.js&lt;/a&gt;&amp;nbsp;is without a doubt the&amp;nbsp;most valuable library(MVL). We used it to layout the circles as well as animate them from their old positions to the new positions each time new data comes in. We also used&amp;nbsp;&lt;a href="http://html5boilerplate.com/"&gt;HTML5 Boilerplate&lt;/a&gt;&amp;nbsp;and&amp;nbsp;&lt;a href="http://jquery.com/"&gt;jQuery&lt;/a&gt;. On the server side, we used&amp;nbsp;&lt;a href="http://expressjs.com/"&gt;express&lt;/a&gt;&amp;nbsp;and the&amp;nbsp;&lt;a href="http://jade-lang.com/"&gt;jade&lt;/a&gt;&amp;nbsp;templating language.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Graphics is done using SVG, which d3.js works very well with - although is independent of.&amp;nbsp;IE8 and below do no support SVG so Twends do not work there.&amp;nbsp;Twends could have worked on IE9 but it doesn't. IE9 supports SVG, so that was not the problem. The problem was that IE9 was blocking the JSONP requests I was making to the Twitter API due to&amp;nbsp;&lt;a href="https://dev.twitter.com/discussions/1232"&gt;this problem&lt;/a&gt;, of which the blame is half on Microsoft and half on Twitter. So, if you go to the site with IE, it will greet you with a friendly(?) message and prompt you to install Google Chrome Frame, yea!&lt;/div&gt;&lt;h2&gt;The Aftermath&lt;/h2&gt;&lt;div&gt;&lt;s&gt;The competition is still being judged at the moment, so I don't know what's the aftermath just yet. I guess I'll update this part of the post another time.&lt;/s&gt;&lt;/div&gt;&lt;div&gt;&lt;s&gt;&lt;br&gt;&lt;/s&gt;&lt;/div&gt;&lt;div&gt;Node knockout came to an end and the&amp;nbsp;&lt;a href="http://nodeknockout.com/"&gt;winners&lt;/a&gt;&amp;nbsp;were victorious! Congrats to them. I am a little disappointed/surprised that one of my favorite entries:&amp;nbsp;&lt;a href="http://kibu.nko2.nodeknockout.com/"&gt;Pitchography&lt;/a&gt;&amp;nbsp;didn't win anything, here's a demo of their&amp;nbsp;&lt;a href="http://www.youtube.com/watch?v=a4gy1s1RzS8"&gt;awesome presentation tool&lt;/a&gt;. As for Twends, well we were decidedly better than half of the entries out there :) We also presented it at the&amp;nbsp;&lt;a href="http://www.meetup.com/AtlantaJavaScript/"&gt;Atlanta Javascript Users Group&lt;/a&gt;&amp;nbsp;and got some good feedback. I've made the source code&amp;nbsp;&lt;a href="https://github.com/airportyh/twends"&gt;public on github&lt;/a&gt;&amp;nbsp;as well.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Node Knockout was a great experience. The organizers did a superb job of allowing the contestants to focus on writing code rather than dealing with setting up servers or administrative stuff. I enjoyed everything from the planning stages where we threw around random ideas, to the actually coding and then to the showing it off to people and seeing their reactions and comments. If you love code, then I highly recommend that you try a hackathon like this one.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;</description>
      <pubDate>Mon, 29 Aug 2011 22:19:07 +0000</pubDate>
      <guid>http://wiki.futuretoby.com/Node_Knockout_2011_and_Twends</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Node_Knockout_2011_and_Twends</link>
    </item>
    <item>
      <title>My JSConf Talk in Video</title>
      <description>The awesome folks behind JSConf just released a&amp;nbsp;&lt;a href="http://blip.tv/jsconf"&gt;whole bunch of great talks in video form&lt;/a&gt;&amp;nbsp;from the Portland event. Great chance to catch up on the talks whether you were there or not! They even put mine up there, which since this is my website, I am obliged to embed here. Wow I sound so very Chinese.&lt;div&gt;&lt;br&gt;&lt;div&gt;&lt;div class="embed" style="width: 550px; height: 393px;"&gt;&lt;span class="embed_indicator"&gt;Embedded Content&lt;/span&gt;&lt;iframe src="http://blip.tv/play/g_Mngs6pEwI.html" width="550" height="393" frameborder="0" allowfullscreen=""&gt;&lt;/iframe&gt;&lt;embed type="application/x-shockwave-flash" src="http://a.blip.tv/api.swf#g_Mngs6pEwI" style="display:none"&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;</description>
      <pubDate>Fri, 19 Aug 2011 15:51:16 +0000</pubDate>
      <guid>http://wiki.futuretoby.com/My_JSConf_Talk_in_Video</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/My_JSConf_Talk_in_Video</link>
    </item>
    <item>
      <title>The Javascript Stacktrace Blog Post</title>
      <description>For the past week or so I did some research on how best to include scripts in &lt;a href="http://tuttijs.com"&gt;Tutti&lt;/a&gt;'s sandbox environment&amp;nbsp;and still get the best stacktraces possible. I got sucked in deeper and deeper and it just got uglier and uglier. This post will attempt to summarize all the knowledge that I've uncovered.&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;What's a Stacktrace?&lt;br&gt;&lt;/h2&gt;&lt;div&gt;When I say stacktrace, I mean it in the context an exception being thrown in your code, and getting the information about where exactly in your code the exception was thrown. This is what a exception might look like&lt;/div&gt;&lt;pre&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: Monaco, monospace; font-size: 13px; -webkit-border-horizontal-spacing: 2px; -webkit-border-vertical-spacing: 2px; line-height: normal; white-space: normal; word-spacing: 0px; "&gt;Error: Buck stops here.&lt;br&gt;at failInlined (http://localhost:8000/error_object/:16:11)&lt;br&gt;at catchError (http://localhost:8000/util.js:77:26)&lt;br&gt;at http://localhost:8000/error_object/:49:1&lt;/span&gt;&lt;br&gt;&lt;/pre&gt;&lt;div&gt;First, there is an error message. Then, the stacktrace. The stacktrace basically&amp;nbsp;represents&amp;nbsp;the state of the program's&amp;nbsp;&lt;a href="http://en.wikipedia.org/wiki/Call_stack"&gt;call stack&lt;/a&gt;&amp;nbsp;at the point when the exception was thrown. The stacktrace also contains the location(file URL and line number) of each call in the stack, which is extremely useful for debugging.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;So What's the Problem?&lt;/h2&gt;&lt;div&gt;The problem, is that not all browsers give you informative stacktraces. Not only that, different browsers give you the information in different ways.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Most browsers today give you the stacktrace information in the Error object that was thrown. In Firefox, Chrome and Opera, for example, the Error object contains a &lt;i&gt;stack&lt;/i&gt; property which is a string representation of the stacktrace, much like the example shown above.&lt;/div&gt;&lt;pre&gt;// Get stacktrace on Firefox, Chrome and Opera&lt;/pre&gt;&lt;pre&gt;try{&lt;/pre&gt;&lt;pre&gt;   throw new Error('Buck stops here')&lt;/pre&gt;&lt;pre&gt;}catch(e){&lt;/pre&gt;&lt;pre&gt;   console.log(e.stack) // Yea!&lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;In Safari, however, the stack property is non-existent: it does not give you the full stacktrace. Instead it gives you the location for the top stack frame only. This is gotten from the properties &lt;i&gt;sourceURL&lt;/i&gt; and &lt;i&gt;line&lt;/i&gt;.&lt;/div&gt;&lt;pre&gt;// Get 1-level stacktrace on Safari&lt;/pre&gt;&lt;pre&gt;try{&lt;/pre&gt;&lt;pre&gt;  throw new Error('Buck stops here')&lt;/pre&gt;&lt;pre&gt;}catch(e){&lt;/pre&gt;&lt;pre&gt;  console.log(e.sourceURL + ': ' + e.line) // Meh&lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;On IE, you are out of luck. There is no stacktrace information available on the Error object.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;Going Deeper&lt;/h2&gt;&lt;div&gt;Javascript can be executed in various different ways/techniques, and not all of them yield good stacktraces. My next objective was to see what the stacktraces look like for the different techniques&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h3&gt;Technique 1: Script Tag Includes&lt;/h3&gt;&lt;div&gt;The script tag include is probably the most common way to execute Javascript on a webpage.&lt;/div&gt;&lt;pre&gt;&amp;lt;script src="myscript.js"&amp;gt;&amp;lt;/script&amp;gt;&lt;/pre&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h3&gt;Technique 2: Inlined Script Tag&lt;/h3&gt;&lt;div&gt;Alternatively you can inlined Javascript code inside of the script tag.&lt;/div&gt;&lt;pre&gt;&amp;lt;script&amp;gt;&lt;/pre&gt;&lt;pre&gt;console.log('Hello world')&lt;/pre&gt;&lt;pre&gt;&amp;lt;/script&amp;gt;&lt;/pre&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h3&gt;Technique 3: Dynamically Inserted Script Tag&lt;/h3&gt;&lt;div&gt;You can also create a script element dynamically in Javascript and load some Javascript into it.&lt;/div&gt;&lt;pre&gt;var script = document.createElement('script')&lt;/pre&gt;&lt;pre&gt;if (&amp;lt;IE sucks and you are it&amp;gt;)&lt;/pre&gt;&lt;pre&gt;  script.text = jsCode&lt;/pre&gt;&lt;pre&gt;else&lt;/pre&gt;&lt;pre&gt;  script.appendChild(document.createTextNode(jsCode))&lt;/pre&gt;&lt;pre&gt;document.body.appendChild(script)&lt;/pre&gt;&lt;pre&gt;document.body.removeChild(script)&lt;/pre&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h3&gt;Technique 4: Eval&lt;/h3&gt;&lt;div&gt;Use eval to execute the Javascript in Javascript. You probably want to&amp;nbsp;&lt;a href="http://perfectionkills.com/global-eval-what-are-the-options/"&gt;global eval&lt;/a&gt;&amp;nbsp;it.&lt;/div&gt;&lt;pre&gt;// This code for global eval stolen from jQuery 1.6.1&lt;/pre&gt;&lt;pre&gt;(window.execScript || function(jsCode) {
	window["eval"].call(window, jsCode);
} )(data);&lt;br&gt;&lt;/pre&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h3&gt;Technique 5: Data URL in the Script Tag&lt;br&gt;&lt;/h3&gt;&lt;div&gt;Using a data URL in a script tag is...I am not sure if anyone actually does this, and I am not entirely sure it's useful, but what the heck.&lt;/div&gt;&lt;pre&gt;&amp;lt;script url="data:application/javascript,console.log('hello%20world')"&amp;gt;&amp;lt;/script&amp;gt;&lt;/pre&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h3&gt;Summary: Stacktrace Information From Error Object&lt;/h3&gt;&lt;div&gt;Long story short, I tested the stacktrace output for each of these five techniques in different browsers. I summarized the results in this here table (that's right, geek out!)&lt;/div&gt;&lt;div&gt;&lt;style&gt;
table#support,
#definitions
{
    font-family: Helvetica, "sans serif";
}
table#support{
    width: 100%;
    border-collapse: collapse;
}
table#support th,
table#support td{
    border: 1px solid #aaa;
    text-align: center;
}

#definitions dt, 
#definitions dd{
}
#definitions dt{
    float: left;
    clear: left;
    font-weight: bold;
}
#definitions dd{
    margin-left: 5em;
}
&lt;/style&gt;
&lt;table id="support"&gt;
    &lt;tbody&gt;&lt;tr&gt;
        &lt;th rowspan="2"&gt;Browser&lt;/th&gt;
        &lt;th colspan="4" title="Script tag with `src` URL attribute"&gt;Include&lt;/th&gt;
        &lt;th colspan="4" title="Inlined script tag"&gt;Inlined&lt;/th&gt;
        &lt;th colspan="4" title="Dynamically inserted inlined script tag"&gt;Dynamic&lt;/th&gt;
        &lt;th colspan="4" title="Global Eval'ed Javascript"&gt;Eval'ed&lt;/th&gt;
        &lt;th colspan="4" title="Script tag with `src` as a Data URL"&gt;Data URL&lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;th title="Line Number"&gt;LN&lt;/th&gt;
        &lt;th title="Source File URL"&gt;SR&lt;/th&gt;
        &lt;th title="Stacktrace"&gt;ST&lt;/th&gt;
        &lt;th title="Call arguments in Stacktrace"&gt;AG&lt;/th&gt;
        &lt;th title="Line Number"&gt;LN&lt;/th&gt;
        &lt;th title="Source File URL"&gt;SR&lt;/th&gt;
        &lt;th title="Stacktrace"&gt;ST&lt;/th&gt;
        &lt;th title="Call arguments in Stacktrace"&gt;AG&lt;/th&gt;
        &lt;th title="Line Number"&gt;LN&lt;/th&gt;
        &lt;th title="Source File URL"&gt;SR&lt;/th&gt;
        &lt;th title="Stacktrace"&gt;ST&lt;/th&gt;
        &lt;th title="Call arguments in Stacktrace"&gt;AG&lt;/th&gt;
        &lt;th title="Line Number"&gt;LN&lt;/th&gt;
        &lt;th title="Source File URL"&gt;SR&lt;/th&gt;
        &lt;th title="Stacktrace"&gt;ST&lt;/th&gt;
        &lt;th title="Call arguments in Stacktrace"&gt;AG&lt;/th&gt;
        &lt;th title="Line Number"&gt;LN&lt;/th&gt;
        &lt;th title="Source File URL"&gt;SR&lt;/th&gt;
        &lt;th title="Stacktrace"&gt;ST&lt;/th&gt;
        &lt;th title="Call arguments in Stacktrace"&gt;AG&lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;IE 6 - 8&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td colspan="4"&gt;Unsupported&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;IE 9&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;Safari 5&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;Y*&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;Y*&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;Chrome 11&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;Y*&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;Y*&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;Y*&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;Firefox 3.6 - 4&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y*&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y*&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y*&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;Opera 11&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;Y*&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;Y*&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
        &lt;td&gt;Y*&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;Y&lt;/td&gt;
        &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;dl id="definitions"&gt;
    &lt;dt&gt;*&lt;/dt&gt;&lt;dd&gt;Line number may not be helpful&lt;/dd&gt;
    &lt;dt&gt;LN&lt;/dt&gt;&lt;dd&gt;Line numbers&lt;/dd&gt;
    &lt;dt&gt;SR&lt;/dt&gt;&lt;dd&gt;Source file URL&lt;/dd&gt;
    &lt;dt&gt;ST&lt;/dt&gt;&lt;dd&gt;Full stacktrace&lt;/dd&gt;
    &lt;dt&gt;AG&lt;/dt&gt;&lt;dd&gt;Call arguments in stacktrace&lt;/dd&gt;
    &lt;dt&gt;Include&lt;/dt&gt;&lt;dd&gt;Script tag with &lt;code&gt;src&lt;/code&gt; set to a Javasrcipt file URL&lt;/dd&gt;
    &lt;dt&gt;Inlined&lt;/dt&gt;&lt;dd&gt;Script tag with inlined Javascript&lt;/dd&gt;
    &lt;dt&gt;Dynamic&lt;/dt&gt;&lt;dd&gt;Dynamically inserted script tag with inlined Javascript&lt;/dd&gt;
    &lt;dt&gt;Eval'ed&lt;/dt&gt;&lt;dd&gt;Global eval'ed Javascript&lt;/dd&gt;
    &lt;dt&gt;Data URL&lt;/dt&gt;&lt;dd&gt;Script tag with &lt;code&gt;src&lt;/code&gt; set to a Data URL containing Javascript&lt;/dd&gt;&lt;/dl&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;A straightforward script tag include yields the best stacktrace information. As the asterisk(*) indicates, the dynamic script element, global eval, and data URL techniques can yield stacktraces with non-helpful line numbers. The data URL technique actually gives correct line numbers, it's just that all the newlines have been encoded and the entire source jammed onto a single line - so, I can't really say the line numbers are all that helpful. Strangly, Opera yields non-helpful line numbers even with the Javascript-inline-in-a-script tag technique.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;So That's it? No IE?&lt;/h2&gt;&lt;div&gt;There's no way to get stack information on IE, not unless you want to do the other thing, but you don't want to know about that.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;What's that? You &lt;i&gt;do&lt;/i&gt; want to know? No you do not! Just forget I said anything.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Okay! I'll tell you, but you are going to regret it.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h3&gt;window.onerror&lt;br&gt;&lt;/h3&gt;&lt;div&gt;On IE - and as it happens on Firefox and Chrome as well - you can register an onerror handler on the window object, like so&lt;/div&gt;&lt;pre&gt;window.onerror = function(message, fileURL, lineNumber){&lt;/pre&gt;&lt;pre&gt;  log(message + ': ' + fileURL + ': ' + lineNumber)&lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;div&gt;The handler will be called anytime a thrown exception is uncaught: propagates all the way to the bottom of the call stack with no catchers. Catching the exception will cause the handler not to be called, unless you rethrow it, but even then, there are other complications. When the handler is called, there is no error object, only the error message, file URL, and the line number.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h3&gt;Bad News: IE&lt;br&gt;&lt;/h3&gt;&lt;div&gt;Because of various IE bugs, the fileURL and line number passed into the &lt;i&gt;onerror&lt;/i&gt; handler isn't always accurate or helpful. After some research, I've isolated these bugs:&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;In IE 7 and below, if an exception is thrown from within the code of an included script, &lt;i&gt;fileURL&lt;/i&gt;&amp;nbsp;will erroneously be set to the URL of the current HTML document even though the lineNumber will be set to the correct line number from within the script.&lt;/li&gt;&lt;li&gt;In IE 8 and below, if an exception is thrown using the throw statement, (i.e. &lt;i&gt;throw new Error()&lt;/i&gt; ) and is caught, and then re-thrown, and then propagates all the way up, the line number reported will be the the place it was re-thrown, rather than the place it was first thrown. This bug does not surface when the error is triggered otherwise, such as with type and reference errors.&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;IE 9 has both of these bugs fixed, even when it emulates older versions of the browser.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;What Can You Throw&lt;/h2&gt;&lt;div&gt;The "throw" statement lets you throw just about any old value - even numbers and strings! But this is not recommended as you won't be able to get any line numbers or stacktraces if the value thrown isn't an object - except for in IE, where you &lt;i&gt;can&lt;/i&gt; get line numbers using &lt;i&gt;onerror&lt;/i&gt;. In IE, throwing anything other than a pre-defined error object(Error, TypeError, etc) will result in the loss of a meaningful message in both the caught error object and in the &lt;i&gt;onerror&lt;/i&gt; handler - where it will just say "Exception thrown and not caught".&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;So, the simplest recommendation here is to only throw the pre-defined &lt;i&gt;Error&lt;/i&gt; object when you want to explicitly throw an error using the "throw" statement.&lt;/div&gt;&lt;pre&gt;throw new Error('Buck stops here.')&lt;/pre&gt;&lt;div&gt;or better yet, don't use the throw statement at all(this avoids the second IE bug mentioned earlier).&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;The DIY Stacktrace&lt;/h2&gt;&lt;div&gt;The DIY stacktrace was pioneered by&amp;nbsp;&lt;a href="http://eriwen.com/javascript/js-stack-trace/"&gt;Eric Wendelin&lt;/a&gt;&amp;nbsp;among others. It first looks up argument.callee to get the current function being executed, then it walks the call stack by accessing the function's &lt;i&gt;caller&lt;/i&gt; attribute recursively. For example:&lt;/div&gt;&lt;pre&gt;&amp;gt; function f(){&lt;/pre&gt;&lt;pre&gt;    g()&lt;/pre&gt;&lt;pre&gt;  }&lt;/pre&gt;&lt;pre&gt;&amp;gt; function g(){&lt;/pre&gt;&lt;pre&gt;    h()&lt;/pre&gt;&lt;pre&gt;  }&lt;/pre&gt;&lt;pre&gt;&amp;gt; function h(){&lt;/pre&gt;&lt;pre&gt;    console.log(arguments.callee.caller.caller)&lt;/pre&gt;&lt;pre&gt;  }&lt;/pre&gt;&lt;pre&gt;&amp;gt; f()&lt;/pre&gt;&lt;pre&gt;function f(){&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;  g()&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;}&lt;/pre&gt;&lt;div&gt;In the example, we are able to access the function &lt;i&gt;f&lt;/i&gt; from with the body of &lt;i&gt;h&lt;/i&gt;'s execution by walking two levels up the call stack using the caller attribute.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h3&gt;Pros and Cons of the DIY Stacktrace&lt;br&gt;&lt;/h3&gt;&lt;div&gt;The advantage of the DIY stacktrace is that it will work in any browser.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;The disadvantages are&lt;/div&gt;&lt;div&gt;&lt;ol&gt;&lt;li&gt;It will not get you file locations/line numbers.&lt;/li&gt;&lt;li&gt;It does not work with thrown errors - either implicitly or explicitly - because the building of the stacktrace needs to be explicited done as its own statement, say, &lt;i&gt;printStackTrace&lt;/i&gt;, for example. So, you cannot have a stacktrace &lt;i&gt;and&lt;/i&gt; an error thrown - &lt;i&gt;you cannot have your cake and eat it too&lt;/i&gt;.&lt;/li&gt;&lt;/ol&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;/div&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;div&gt;Sorry I don't have a better conclusion than: &lt;i&gt;It's a great big mess&lt;/i&gt;. However, with the knowledge covered here, I think it is possible to employ some sophisticated hackery to recover at least &lt;i&gt;some&lt;/i&gt; stacktrace info for each browser - the hardest case being IE. Such a technique - if made practical - would be useful for unit test frameworks and crash reporting.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;References&lt;br&gt;&lt;/h2&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;Eric Wendelin's&amp;nbsp;&lt;a href="http://eriwen.com/javascript/js-stack-trace/"&gt;Javascript Stacktrace&lt;/a&gt;&amp;nbsp;(&amp;nbsp;&lt;a href="https://github.com/eriwen/javascript-stacktrace"&gt;GitHub repo&lt;/a&gt;&amp;nbsp;)&lt;br&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://helephant.com/2007/05/12/diy-javascript-stack-trace/"&gt;DIY Stacktrace&lt;/a&gt;&amp;nbsp;-&amp;nbsp;Helen Emerson&lt;/li&gt;&lt;li&gt;&lt;a href="http://blog.yoursway.com/2009/07/3-painful-ways-to-obtain-stack-trace-in.html"&gt;3 painful ways to obtain a stacktrace&lt;/a&gt;&amp;nbsp;from Your Sway/CrashKit&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;</description>
      <pubDate>Wed, 08 Jun 2011 21:44:11 +0000</pubDate>
      <guid>http://wiki.futuretoby.com/The_Javascript_Stacktrace_Blog_Post</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/The_Javascript_Stacktrace_Blog_Post</link>
    </item>
    <item>
      <title>Try Traceur</title>
      <description>I screwed around with&amp;nbsp;&lt;a href="http://code.google.com/p/traceur-compiler/"&gt;Traceur&lt;/a&gt;&amp;nbsp;last night and this morning. Then I built this thing called&amp;nbsp;&lt;a href="http://trytraceur.tobyho.com/"&gt;Try Traceur&lt;/a&gt;&amp;nbsp;to make it easy for folk to screw around with it too. Try it! You know you want to.</description>
      <pubDate>Thu, 19 May 2011 15:12:51 +0000</pubDate>
      <guid>http://wiki.futuretoby.com/Try_Traceur</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Try_Traceur</link>
    </item>
    <item>
      <title>JSConf Summary and My Codez</title>
      <description>JSConf 2011 Portland was truly amazing experience for me, personally. Not only did I meet some fantastic people in the community - some of whom I've long wanted to meet, I also got to show off&amp;nbsp;&lt;a href="http://tuttijs.com/"&gt;my stuff&lt;/a&gt;, and it didn't totally suck. Also, add to that, Portland is a fantastic city! I want to thank Chris Williams again for motivating me, and everybody involved for such a great event!&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;My talk was on&amp;nbsp;&lt;a href="http://tuttijs.com/"&gt;Tutti&lt;/a&gt;&amp;nbsp;and most of its time was occupied by demos, so rather than posting the slides I thought I would just post the&amp;nbsp;&lt;a href="https://github.com/airportyh/Tutti-JSConf-Code-Examples"&gt;example code&lt;/a&gt;&amp;nbsp;for the demos. I hope this is helpful to people!&lt;/div&gt;</description>
      <pubDate>Fri, 06 May 2011 22:25:03 +0000</pubDate>
      <guid>http://wiki.futuretoby.com/JSConf_Summary_and_My_Codez</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/JSConf_Summary_and_My_Codez</link>
    </item>
    <item>
      <title>Tuttiterm - Tutti for your Terminal</title>
      <description>I've created&amp;nbsp;&lt;a href="https://github.com/airportyh/tuttiterm"&gt;Tuttiterm&lt;/a&gt;&amp;nbsp;- which allows you to control browsers via&amp;nbsp;&lt;a href="http://tutti.tobyho.com"&gt;Tutti&lt;/a&gt;. See the project&amp;nbsp;&lt;a href="https://github.com/airportyh/tuttiterm"&gt;README&lt;/a&gt;. Here's a screenshot:&lt;div&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse;"&gt;&lt;img title="Screenshot" alt="Screenshot" src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TXUF6UN4C4I/AAAAAAAARlk/Z2koe-4Nn-A/s800/Screen%20shot%202011-03-07%20at%2010.05.08%20AM.jpg"&gt;&lt;br&gt;&lt;/span&gt;&lt;/div&gt;</description>
      <pubDate>Fri, 04 Mar 2011 07:23:16 +0000</pubDate>
      <guid>http://wiki.futuretoby.com/Tuttiterm_-_Tutti_for_your_Terminal</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Tuttiterm_-_Tutti_for_your_Terminal</link>
    </item>
    <item>
      <title>Testing Tip: The Dummy Function</title>
      <description>Sometimes when you are writing tests, you find yourself testing whether a particular callback has been called. For example, you might write a test like this&lt;pre&gt;&lt;span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', Verdana, Helvetica, Arial; font-size: 18px; white-space: normal; "&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;var lastCalledWith&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;function callback(e){&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;    lastCalledWith = e&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;}&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;obj.bind('someevent', callback)&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;obj.doSomethingThatShouldTriggerEvent()&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;expect(lastCalledWith.type).toBe('someevent') // check that callback was called&lt;/pre&gt;&lt;/span&gt;&lt;/pre&gt;&lt;div&gt;This is slightly tedious and the code ungainly because you need to introduce a variable in your test, and store the arguments to it so that you can check the result. We can do better&lt;/div&gt;&lt;pre&gt;function $dummy(){&lt;/pre&gt;&lt;pre&gt;    arguments.callee.lastCalledWith = arguments&lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;pre&gt;obj.bind('someevent', $dummy)&lt;/pre&gt;&lt;pre&gt;obj.doSomethingThatShouldTriggerEvent()&lt;/pre&gt;&lt;pre&gt;expect($dummy.lastCalledWith[0].type).toBe('someevent')&lt;/pre&gt;&lt;div&gt;This is a nice and generic, but we have to reset the lastCalledWith attribute before each test, something like&lt;/div&gt;&lt;pre&gt;delete $dummy.lastCalledWith&lt;/pre&gt;&lt;div&gt;But let's make it more painless&lt;/div&gt;&lt;pre&gt;$dummy.reset()&lt;/pre&gt;&lt;div&gt;By adding this reset function&lt;/div&gt;&lt;pre&gt;$dummy.reset = function(){
    delete this.lastCalledWith
    return this
}&lt;br&gt;&lt;/pre&gt;&lt;div&gt;Moreover, reset returns back the dummy function itself, so, now you can write the test like so&lt;/div&gt;&lt;pre&gt;&lt;span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', Verdana, Helvetica, Arial; font-size: 18px; white-space: normal; "&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;obj.bind('someevent', $dummy.reset())&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;obj.doSomethingThatShouldTriggerEvent()&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;expect($dummy.lastCalledWith[0].type).toBe('someevent')&lt;/pre&gt;&lt;/span&gt;&lt;/pre&gt;&lt;div&gt;Very nice. I like.&lt;/div&gt;</description>
      <pubDate>Fri, 25 Feb 2011 11:37:29 +0000</pubDate>
      <guid>http://wiki.futuretoby.com/Testing_Tip%3A_The_Dummy_Function</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Testing_Tip%3A_The_Dummy_Function</link>
    </item>
    <item>
      <title>Playing With Self</title>
      <description>The&amp;nbsp;&lt;a href="http://selflanguage.org/"&gt;Self Language&lt;/a&gt;&amp;nbsp;is a descendant of Smalltalk, and is the language that introduced the concept of prototype inheritance. To get a historical perspective, I wanted to try it out, and luckily, it is still available online&amp;nbsp;&lt;a href="http://selflanguage.org/"&gt;despite&lt;/a&gt;&amp;nbsp;Sun killing the project in '95.&lt;h2&gt;Install&lt;/h2&gt;&lt;div&gt;To install Self, go to its&amp;nbsp;&lt;a href="http://selflanguage.org/download/index.html"&gt;download page&lt;/a&gt;&amp;nbsp;and follow the instructions. In short, first, you need to install the VM by running the installer. Next, you need to download a snapshot image. There are two to choose from: the&amp;nbsp;&lt;a href="http://selflanguage.org/files/releases/4.4/Clean-4.4.snap"&gt;clean&lt;/a&gt;(spic 'n span)&amp;nbsp;and the&amp;nbsp;&lt;a href="http://selflanguage.org/files/releases/4.4/Demo-4.4.snap"&gt;demo&lt;/a&gt;(kitchen sink). Next, double click on the image that you downloaded, and you should be good to go.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;I am going to do a walkthrough using the clean image because I just want to try out some basic language features. When the environment - or "world" - finishes launching, you are greeted with a large gray space with a shell window on the top left, and a trash can on the top right.&lt;/div&gt;&lt;div&gt;&lt;img title="Clean Image" alt="Clean Image" src="https://lh6.googleusercontent.com/_1m4jxPGXQAo/TV8qdaQJQBI/AAAAAAAARdo/XS3Mrc_LXvA/s800/Screen%20shot%202011-02-18%20at%209.26.28%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;So, let's play around and see how prototype inheritance works in Self. To create a new empty object, type&lt;/div&gt;&lt;pre&gt;()&lt;/pre&gt;&lt;div&gt;into the shell window and then click the "Get it" button. You should see a new expandable window that says "a slots object". If you expand it, it should look like&lt;/div&gt;&lt;div&gt;&lt;i&gt;&lt;img title="New Empty Object" alt="New Empty Object" src="https://lh6.googleusercontent.com/_1m4jxPGXQAo/TV8rKl2I53I/AAAAAAAARds/QfqTfuGZhYM/s800/Screen%20shot%202011-02-18%20at%209.29.46%20PM.jpg"&gt;&lt;/i&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;This is an empty object, the equivalent of &lt;i&gt;{}&lt;/i&gt; in Javascript.&amp;nbsp;&lt;/div&gt;&lt;h2&gt;Slots&lt;/h2&gt;&lt;div&gt;Now let's add some attributes to it, except in Self, we call them &lt;i&gt;slots&lt;/i&gt;. Right-click on the header of this window and select "Add Slot". You should see this&lt;/div&gt;&lt;div&gt;&lt;img title="Adding a Slot" alt="Adding a Slot" src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TV8r5a8SAvI/AAAAAAAARd8/-DTDjSTsZl0/s800/Screen%20shot%202011-02-18%20at%209.32.55%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;This textarea is where you would write the code for either a value slot or a method slot. The textarea preloads with some examples of what you can write here.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;We are going to just add a read-only slot&lt;/div&gt;&lt;div&gt;&lt;img title="Thelonious" alt="Thelonious" src="https://lh4.googleusercontent.com/_1m4jxPGXQAo/TV8s0vHOFII/AAAAAAAAReQ/MJWXbe2ASKI/s800/Screen%20shot%202011-02-18%20at%209.36.27%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Just so you know, a read/write value slot would be written as&lt;/div&gt;&lt;pre&gt;name &amp;lt;- 'Thelonious'&lt;/pre&gt;&lt;div&gt;When you are done, click on the thin green vertical bar on the left side of the window, and it should except the code. If your code has a syntax error, it will complain, and you'll need to try again. If you got it right, you should see this&lt;/div&gt;&lt;div&gt;&lt;img title="Thelonious Success" alt="Thelonious Success" src="https://lh4.googleusercontent.com/_1m4jxPGXQAo/TV8tcsN-MdI/AAAAAAAAReg/R8y32gI3mi4/s800/Screen%20shot%202011-02-18%20at%209.39.29%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;For fun, let's make a few more slots. Repeat the "Add Slot" procedure, but this time add a &lt;i&gt;hair&lt;/i&gt; slot and set it to 'dark and curly', add a &lt;i&gt;plays&lt;/i&gt; slot and set it to 'piano'. If things go right you should see&lt;/div&gt;&lt;div&gt;&lt;img title="Slots" alt="Slots" src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TV8125mM-QI/AAAAAAAARhE/rb_20xeaNi4/s800/Screen%20shot%202011-02-18%20at%2010.15.19%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Now, click on the "E" button to get an evaluation console. If you type&lt;/div&gt;&lt;pre&gt;plays&lt;/pre&gt;&lt;div&gt;into it and click "Get it", you should get the string 'piano' to come out&lt;/div&gt;&lt;div&gt;&lt;img title="Get Slot Value" alt="Get Slot Value" src="https://lh6.googleusercontent.com/_1m4jxPGXQAo/TV82Fa7dmwI/AAAAAAAARhU/o5xPTK76Xjc/s800/Screen%20shot%202011-02-18%20at%2010.16.20%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Okay, so it gets the value correctly.&lt;/div&gt;&lt;h2&gt;Inheritance&lt;/h2&gt;&lt;div&gt;Cool. Next we are going to create the inheritance link. First, we create an empty object again to represent the child.&lt;/div&gt;&lt;div&gt;&lt;img title="Empty Object" alt="Empty Object" src="https://lh6.googleusercontent.com/_1m4jxPGXQAo/TV8rKl2I53I/AAAAAAAARds/QfqTfuGZhYM/s800/Screen%20shot%202011-02-18%20at%209.29.46%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Now, we add a special slot and call it &lt;i&gt;parent*&lt;/i&gt;.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;img title="Parent link" alt="Parent link" src="https://lh6.googleusercontent.com/_1m4jxPGXQAo/TV8xt5NX5PI/AAAAAAAARfQ/PRjq3wdfzJ8/s800/Screen%20shot%202011-02-18%20at%209.55.17%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;We don't set it to a value so that it defaults to &lt;i&gt;nil&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;img title="Made parent link" alt="Made parent link" src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TV8yCyAUW0I/AAAAAAAARfo/zIT768Zc2pE/s800/Screen%20shot%202011-02-18%20at%209.58.35%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Next, we need to link it to &lt;i&gt;Thelonious&lt;/i&gt;. First click on the little button with two small dots just to the right of the &lt;i&gt;nil&lt;/i&gt;. The &lt;i&gt;nil&lt;/i&gt;&amp;nbsp;object will come out and you'll see a link from your &lt;i&gt;parent*&lt;/i&gt;&amp;nbsp;slot to it.&lt;/div&gt;&lt;div&gt;&lt;img title="nil" alt="nil" src="https://lh6.googleusercontent.com/_1m4jxPGXQAo/TV8ypdNJbaI/AAAAAAAARfs/VXousvCEERs/s800/Screen%20shot%202011-02-18%20at%2010.01.40%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;In Self, any slot that ends in * is a parent link. So, in fact, it supports &lt;i&gt;multiple inheritance&lt;/i&gt;! Anyway, we are close to completing the inheritance. Now just drag the link to &lt;i&gt;Thelonious. &lt;/i&gt;If you got it, you'll see this&lt;/div&gt;&lt;div&gt;&lt;img title="Linked" alt="Linked" src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TV82UAODeeI/AAAAAAAARhY/w89LNExdx_g/s800/Screen%20shot%202011-02-18%20at%2010.17.21%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Now, to test that it worked, click on "E" in the child object and type&lt;/div&gt;&lt;pre&gt;hair&lt;/pre&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;img title="Inheritance at work" alt="Inheritance at work" src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TV81WrjZ2xI/AAAAAAAARg0/BZ2f1YwUB_E/s800/Screen%20shot%202011-02-18%20at%2010.13.04%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Sweet! Now, we can override slots in the child, right?&lt;/div&gt;&lt;div&gt;&lt;img title="Slot override" alt="Slot override" src="https://lh4.googleusercontent.com/_1m4jxPGXQAo/TV821FEwjOI/AAAAAAAARho/YT5Rq-J8h9w/s800/Screen%20shot%202011-02-18%20at%2010.19.19%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Yup. While we are at it, we'll change the name to 'Thelonious Jr.' too.&lt;/div&gt;&lt;h2&gt;Methods&lt;/h2&gt;&lt;div&gt;Next, let's create a method. Let's create a &lt;i&gt;greet&lt;/i&gt;&amp;nbsp;method on the parent. The &lt;i&gt;greet&lt;/i&gt; method will simply popup an alert dialog with the message. It does this using the &lt;i&gt;report:&lt;/i&gt;&amp;nbsp;method of &lt;i&gt;userQuery&lt;/i&gt;.&lt;/div&gt;&lt;pre&gt;userQuery report: 'Hi, I am ', name, ', I have ', hair, 
   ' hair and I play the ', plays, '.'&lt;br&gt;&lt;/pre&gt;&lt;div&gt;But, this won't work. Try running it - by clicking "Do it" will give you&lt;/div&gt;&lt;div&gt;&lt;img title="Error userQuery" alt="Error userQuery" src="https://lh4.googleusercontent.com/_1m4jxPGXQAo/TV8_o7fR2QI/AAAAAAAARh8/iVFmXzX3vjI/s800/Screen%20shot%202011-02-18%20at%2010.57.08%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;It couldn't find the &lt;i&gt;userQuery &lt;/i&gt;object within its slots. In Self, the normal convention is to have your object inherit the &lt;i&gt;lobby&lt;/i&gt;&amp;nbsp;object in order to have access to all the global variables(this is like the global object in Javascript, aka the &lt;i&gt;public restroom&lt;/i&gt;). So okay, we have 'Thelonious' inherit lobby using a link called &lt;i&gt;lobby*&lt;/i&gt;. To do this, we first get hold of the lobby object by typing in the shell&lt;/div&gt;&lt;pre&gt;lobby&lt;/pre&gt;&lt;div&gt;and clicking "Get it". Then, create a slot on 'Thelonious' called &lt;i&gt;lobby*&lt;/i&gt;&amp;nbsp;and like to it. You should end up with this&lt;/div&gt;&lt;div&gt;&lt;img title="link to lobby" alt="link to lobby" src="https://lh4.googleusercontent.com/_1m4jxPGXQAo/TV9A7BW0CzI/AAAAAAAARiQ/XhiBaE5RnGY/s800/Screen%20shot%202011-02-18%20at%2011.02.38%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Now, if you try "Do it" on &lt;i&gt;greet&lt;/i&gt;&amp;nbsp;it should give you&lt;/div&gt;&lt;div&gt;&lt;img title="Greet" alt="Greet" src="https://lh6.googleusercontent.com/_1m4jxPGXQAo/TV9EYoWwz-I/AAAAAAAARjE/oJM87SljTyg/s800/Screen%20shot%202011-02-18%20at%2011.17.23%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;And 'Thelonious Jr.' should also be able to do this&lt;/div&gt;&lt;div&gt;&lt;img title="Jr Greet" alt="Jr Greet" src="https://lh3.googleusercontent.com/_1m4jxPGXQAo/TV9Em_tI1xI/AAAAAAAARjU/NektO3o-05c/s800/Screen%20shot%202011-02-18%20at%2011.18.23%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Sweet!&lt;/div&gt;&lt;h2&gt;Comparison With Javascript&lt;/h2&gt;&lt;div&gt;With a cursory look at the language Self, here are some of the differences between it and Javascript:&lt;/div&gt;&lt;div&gt;&lt;ol&gt;&lt;li&gt;It supports multiple inheritance, name clashes will result in a runtime error.&lt;/li&gt;&lt;li&gt;Implicit self. No need to write "&lt;i&gt;this."&lt;/i&gt;&amp;nbsp;within the method body like Javascript.&lt;/li&gt;&lt;li&gt;It differentiates between methods and blocks(in Javascript they are both functions). For this reason, you won't have the ugly Javascript problem of having to manually store a reference to &lt;i&gt;this&lt;/i&gt;&amp;nbsp;when you want to use it in inner blocks within a method.&lt;/li&gt;&lt;li&gt;There's no constructor. You construct object using literals or by cloning another object.&lt;/li&gt;&lt;li&gt;Reflection is done with a special mirror object attached each object's&amp;nbsp;&lt;i&gt;_Mirror&lt;/i&gt;&amp;nbsp;slot.&lt;/li&gt;&lt;li&gt;There is support for referencing a &lt;i&gt;super &lt;/i&gt;method using a special &lt;i&gt;resend&amp;nbsp;&lt;/i&gt;syntax.&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;</description>
      <pubDate>Fri, 18 Feb 2011 21:21:54 +0000</pubDate>
      <guid>http://wiki.futuretoby.com/Playing_With_Self</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Playing_With_Self</link>
    </item>
    <item>
      <title>Checking Types in Javascript</title>
      <description>Have you ever wondered: &lt;i&gt;what is the correct way to check if a Javascript variable is an Array?&lt;/i&gt;&lt;div&gt;&lt;i&gt;&lt;br&gt;&lt;/i&gt;&lt;/div&gt;&lt;div&gt;Do a Google search and you will get a great variety of answers. And, unfortunately, there's &lt;i&gt;is&lt;/i&gt;&amp;nbsp;no correct answer. This is one of the sad things about Javascript, not only are there many varying implementations of the language, there are also many varying opinions about how things should be done.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Enough philosophizing and feeling sorry about the state of things. With this article, I will trying to give a comprehensive overview of the different techniques of checking-types in Javascript, the pros and cons of each and why they exist.&lt;/div&gt;&lt;h2&gt;&lt;i&gt;typeof&lt;/i&gt;&amp;nbsp;operator&lt;/h2&gt;&lt;div&gt;In the beginning, there was &lt;i&gt;typeof. &lt;/i&gt;This handy operator gives you the "type" of a Javascript value:&lt;/div&gt;&lt;pre&gt;typeof 3 // "number"&lt;/pre&gt;&lt;pre&gt;typeof "abc" // "string"&lt;/pre&gt;&lt;pre&gt;typeof {} // "object"&lt;/pre&gt;&lt;pre&gt;typeof true // "boolean"&lt;/pre&gt;&lt;pre&gt;typeof undefined // "undefined"&lt;/pre&gt;&lt;pre&gt;typeof function(){} // "function"&lt;/pre&gt;&lt;div&gt;All is fine 'n dandy until&lt;/div&gt;&lt;pre&gt;typeof [] // "object"&lt;/pre&gt;&lt;div&gt;Huh? An array's type is &lt;i&gt;object&lt;/i&gt;? I guess it &lt;i&gt;is&lt;/i&gt;, if you want to get technical about it, but still, what the...&lt;/div&gt;&lt;pre&gt;typeof null // "object"&lt;/pre&gt;&lt;div&gt;Okay, &lt;i&gt;now&lt;/i&gt;&amp;nbsp;that's just &lt;i&gt;wrong!&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;&lt;br&gt;&lt;/i&gt;&lt;/div&gt;&lt;div&gt;Also, &lt;i&gt;typeof&lt;/i&gt;&amp;nbsp;will return "object" for Dates, RegExp, user defined objects, DOM elements, and pretty much anything else. So, &lt;i&gt;typeof&lt;/i&gt;&amp;nbsp;is pretty good at distinguishing between different kind of primitive values, and distinguish between them and &lt;i&gt;objects&lt;/i&gt;, but is completely useless when it comes to distinguishing between different kinds of objects - &lt;i&gt;which includes arrays and nulls(WTF?!)&lt;/i&gt;.&lt;/div&gt;&lt;h2&gt;&lt;i&gt;instanceof&lt;/i&gt;&amp;nbsp;operator&lt;/h2&gt;&lt;div&gt;The &lt;i&gt;instanceof &lt;/i&gt;operator tells you whether a object is an instance of a certain type. The so-called "type" is a constructor. For example&lt;/div&gt;&lt;pre&gt;function Animal(){}&lt;/pre&gt;&lt;pre&gt;var a = new Animal()&lt;/pre&gt;&lt;pre&gt;a instanceof Animal // true&lt;/pre&gt;&lt;div&gt;Alternatively, you could make this check using the &lt;i&gt;constructor&lt;/i&gt;&amp;nbsp;property of an object&lt;/div&gt;&lt;pre&gt;a.constructor === Animal // true&lt;/pre&gt;&lt;div&gt;However, the constructor check has two problems. First, it does not walk up the prototype chain&lt;/div&gt;&lt;pre&gt;function Cat(){}&lt;/pre&gt;&lt;pre&gt;Cat.prototype = new Animal&lt;/pre&gt;&lt;pre&gt;Cat.prototype.constructor = Cat&lt;/pre&gt;&lt;pre&gt;var felix = new Cat&lt;/pre&gt;&lt;pre&gt;felix instanceof Cat // true&lt;/pre&gt;&lt;pre&gt;felix instanceof Animal // true&lt;/pre&gt;&lt;pre&gt;felix.constructor === Cat // true&lt;/pre&gt;&lt;pre&gt;felix.constructor === Animal // false&lt;/pre&gt;&lt;div&gt;&lt;div&gt;The second problem is that it will bomb out if the object in question is null or undefined.&lt;/div&gt;&lt;pre&gt;felix = null&lt;/pre&gt;&lt;pre&gt;felix instanceof Animal // true&lt;/pre&gt;&lt;pre&gt;felix.constructor === Animal // throws TypeError&lt;/pre&gt;&lt;div&gt;&lt;i&gt;instanceof&amp;nbsp;&lt;/i&gt;works for &lt;i&gt;all&lt;/i&gt; native types!&lt;/div&gt;&lt;/div&gt;&lt;pre&gt;[1, 2, 3] instanceof Array // true&lt;/pre&gt;&lt;pre&gt;/abc/ instanceof RegExp // true&lt;/pre&gt;&lt;pre&gt;({}) instanceof Object // true&lt;/pre&gt;&lt;pre&gt;(function(){}) instanceof Function // true&lt;/pre&gt;&lt;div&gt;or does it?&lt;/div&gt;&lt;pre&gt;3 instanceof Number // false&lt;/pre&gt;&lt;pre&gt;true instanceof Boolean // false&lt;/pre&gt;&lt;pre&gt;'abc' instanceof String // false&lt;/pre&gt;&lt;div&gt;Okay, what is going on here? It turns out that &lt;i&gt;instanceof&lt;/i&gt;&amp;nbsp;does not work with primitive values. The primitive types in Javascript are: &lt;i&gt;strings&lt;/i&gt;, &lt;i&gt;numbers&lt;/i&gt;, &lt;i&gt;booleans&lt;/i&gt;, &lt;i&gt;null&lt;/i&gt;, and &lt;i&gt;undefined&lt;/i&gt; - (Oh good! You can count them all on one hand!) Well actually, I should have said it does not work with primitives with the exception of &lt;i&gt;null&lt;/i&gt; and &lt;i&gt;undefined&lt;/i&gt;, because they are not an instance of anything, and so &lt;i&gt;instanceof&lt;/i&gt; correctly returns false when either is used on the left hand side.&lt;/div&gt;&lt;pre&gt;null instanceof Boolean // false&lt;/pre&gt;&lt;pre&gt;undefined instanceof Array // false&lt;/pre&gt;&lt;div&gt;To top that off though, checking for the constructor property &lt;i&gt;will &lt;/i&gt;work for the primitive types &lt;i&gt;number, string&lt;/i&gt;&amp;nbsp;and &lt;i&gt;boolean&lt;/i&gt;.&lt;/div&gt;&lt;pre&gt;(3).constructor === Number // true&lt;/pre&gt;&lt;pre&gt;true.constructor === Boolean // true&lt;/pre&gt;&lt;pre&gt;'abc'.constructor === String // true&lt;/pre&gt;&lt;div&gt;This works because whenever you reference a property on a primitive value, Javascript will automatically wrap the value with an object wrapper, like so&lt;/div&gt;&lt;pre&gt;var wrapper = new Number(3)&lt;/pre&gt;&lt;div&gt;except you don't see this - it happens behind the scenes. The wrapper then will be an instance of - in this case &lt;i&gt;Number&lt;/i&gt; - or a &lt;i&gt;Boolean&lt;/i&gt; or a &lt;i&gt;String&lt;/i&gt;&amp;nbsp;depending on the type of the primitive value, at which point it can walk up the prototype-chain and get at the properties of the Number prototype, etc. So, for example, creating a wrapper manually will make the &lt;i&gt;instanceof&lt;/i&gt;&amp;nbsp;operator work&lt;/div&gt;&lt;pre&gt;new Number(3) instanceof Number // true&lt;/pre&gt;&lt;pre&gt;new Boolean(true) instanceof Boolean // true&lt;/pre&gt;&lt;pre&gt;new String('abc') instanceof String // true&lt;/pre&gt;&lt;div&gt;But doing that would be pointless because it requires you to already know the type of the value of which you are asking whether or not it is of the type that you already know it is.&lt;/div&gt;&lt;h3&gt;Cross-window Issues of &lt;i&gt;instanceof&lt;/i&gt;&lt;/h3&gt;&lt;div&gt;It turns out that &lt;i&gt;instanceof&lt;/i&gt;&amp;nbsp;has another problem. It breaks down when you try to test an object coming from another window. You know? The ones that are&amp;nbsp;created for each &amp;lt;iframe&amp;gt;, &amp;lt;frame&amp;gt; or popup window that you create.&amp;nbsp;&lt;/div&gt;&lt;pre&gt;&lt;i&gt;var iframe = document.createElement('iframe')&lt;/i&gt;&lt;/pre&gt;&lt;pre&gt;&lt;i&gt;document.body.appendChild(iframe)&lt;/i&gt;&lt;/pre&gt;&lt;pre&gt;&lt;i&gt;var iWindow = iframe.contentWindow // get a reference to the window object of the iframe&lt;/i&gt;&lt;/pre&gt;&lt;pre&gt;&lt;i&gt;iWindow.document.write('&amp;lt;script&amp;gt;var arr = [1, 2, 3]&amp;lt;/script&amp;gt;') // create an array var in iframe's window&lt;/i&gt;&lt;/pre&gt;&lt;pre&gt;&lt;i&gt;iWindow.arr // [1, 2, 3]&lt;/i&gt;&lt;/pre&gt;&lt;pre&gt;&lt;i&gt;iWindow.arr instanceof Array // false&lt;/i&gt;&lt;/pre&gt;&lt;div&gt;Above, we created a variable&amp;nbsp;&lt;i&gt;arr&lt;/i&gt;&amp;nbsp;inside the context of the iframe and set it to the array &lt;i&gt;[1, 2, 3]&lt;/i&gt;. However, we get &lt;i&gt;false&lt;/i&gt;&amp;nbsp;when we ask whether it is a instance of Array. What is happening?!! Behold.&lt;/div&gt;&lt;pre&gt;Array === iWindow.Array // false&lt;/pre&gt;&lt;div&gt;The Array in the iframe is &lt;i&gt;not&lt;/i&gt; the same Array as our Array! This is true for all built-in objects: there are two versions of all of them! Basically, we have parallel universes! OMG!&lt;/div&gt;&lt;div&gt;What this means is that an array created within the iframe is only an instance of the Array constructor within the iframe&lt;/div&gt;&lt;pre&gt;iWindow.arr instanceof iWindow.Array // true&lt;/pre&gt;&lt;div&gt;The same phenomenon happens with windows created using the &lt;i&gt;open()&lt;/i&gt;&amp;nbsp;function.&lt;i&gt;&amp;nbsp;&lt;/i&gt;It is because of this cross-window problem that the use of &lt;i&gt;instanceof&lt;/i&gt;&amp;nbsp;is somewhat limited and discouraged within the Javascript community.&lt;/div&gt;&lt;h3&gt;Duck-Typing&lt;/h3&gt;&lt;div&gt;Because neither &lt;i&gt;typeof&lt;/i&gt;&amp;nbsp;or &lt;i&gt;instanceof &lt;/i&gt;are satisfactory, many resort to duck-typing. This means checking the behavior: i&lt;i&gt;f it looks like a duck and quacks like a duck, then it is a duck as far as I am concerned&lt;/i&gt;. Pretty sure I misquoted that...oh well.&lt;/div&gt;&lt;div&gt;So, using duck-typing, an isArray check might look like&lt;/div&gt;&lt;pre&gt;// source: http://forums.devshed.com/javascript-development-115/javascript-test-whether-a-variable-is-array-or-not-33051.html&lt;/pre&gt;&lt;pre&gt;function isArray(obj){
    return (typeof(obj.length)=="undefined") ?
        false:true;
}&lt;/pre&gt;&lt;div&gt;or&amp;nbsp;&lt;/div&gt;&lt;pre&gt;// source: http://www.hunlock.com/blogs/Ten_Javascript_Tools_Everyone_Should_Have&lt;/pre&gt;&lt;pre&gt;function isArray(testObject) {
    return testObject &amp;amp;&amp;amp;&lt;/pre&gt;&lt;pre&gt;&lt;span class="Apple-tab-span" style="white-space:pre"&gt;	&lt;/span&gt;!(testObject.propertyIsEnumerable('length')) &amp;amp;&amp;amp;&lt;/pre&gt;&lt;pre&gt;&lt;span class="Apple-tab-span" style="white-space:pre"&gt;	&lt;/span&gt;typeof testObject === 'object' &amp;amp;&amp;amp;&lt;/pre&gt;&lt;pre&gt;&lt;span class="Apple-tab-span" style="white-space:pre"&gt;	&lt;/span&gt;typeof testObject.length === 'number';
}&lt;br&gt;&lt;/pre&gt;&lt;div&gt;in jQuery, the function to check whether an object is a window is&lt;/div&gt;&lt;pre&gt;isWindow: function( obj ) {
    return obj &amp;amp;&amp;amp; typeof obj === "object" &amp;amp;&amp;amp; "setInterval" in obj;
}&lt;br&gt;&lt;/pre&gt;&lt;div&gt;You could easily trick this function into returning true&lt;/div&gt;&lt;pre&gt;$.isWindow({setInterval: 'bah!'}) // true&lt;/pre&gt;&lt;div&gt;Clearly, the problem with this approach is that&lt;/div&gt;&lt;div&gt;&lt;ol&gt;&lt;li&gt;it is inexact and can have false positives&lt;/li&gt;&lt;li&gt;the set of properties of the object to test is arbitrary, and so it's unlikely for different people to agree on one way of doing it&lt;/li&gt;&lt;/ol&gt;&lt;div&gt;For the record, I don't like this approach.&lt;/div&gt;&lt;/div&gt;&lt;h3&gt;&lt;i&gt;Object.prototype.toString&lt;/i&gt; method&lt;/h3&gt;&lt;div&gt;It turns out that, you can get type information about an object by using the &lt;i&gt;Object.prototype.toString&lt;/i&gt;&amp;nbsp;method.&lt;/div&gt;&lt;pre&gt;Object.prototype.toString.call(3) // "[object Number]"&lt;/pre&gt;&lt;pre&gt;Object.prototype.toString.call([1, 2, 3]) // "[object Array]"&lt;/pre&gt;&lt;pre&gt;Object.prototype.toString.call({}) // "[object Object]"&lt;/pre&gt;&lt;div&gt;This native method is rarely encountered normally because it's usually shadowed by another toString method lower down in the prototype chain(Array.prototype.toString, Number.prototype.toString, etc.). This method reliably differentiates between native types, however, will return "[object Object]" for all user-defined types&lt;/div&gt;&lt;pre&gt;Object.prototype.toString.call(new Animal) // "[object Object]"&lt;/pre&gt;&lt;div&gt;It does, however, work across different window contexts&lt;/div&gt;&lt;pre&gt;Object.prototype.toString.call(iWindow.arr) === "[object Array]" // true&lt;br&gt;&lt;/pre&gt;&lt;div&gt;with one exception: different windows(as in popup window) in IE.&lt;br&gt;&lt;/div&gt;&lt;pre&gt;var pWindow = open("")&lt;/pre&gt;&lt;pre&gt;pWindow.document.write('&amp;lt;script&amp;gt;var arr = [1, 2, 3]&amp;lt;/script&amp;gt;')&lt;/pre&gt;&lt;pre&gt;Object.prototype.toString.call(pWindow.arr) // you get "[object Object]" in IE; "[object Array]" else where.&lt;/pre&gt;&lt;div&gt;This is strange because for &lt;i&gt;iframes&lt;/i&gt;&amp;nbsp;it works just fine, bummer!&amp;nbsp;This method has become somewhat of a preferred way to differentiate native types despite the IE bug. &lt;i&gt;Ehh, nobody uses popup windows anymore anyway.&lt;/i&gt;&lt;/div&gt;&lt;h3&gt;&lt;i&gt;Function.prototype.toString&lt;/i&gt; method&lt;/h3&gt;&lt;div&gt;Yet another way to test for type information is by using the &lt;i&gt;Function.prototype.toString &lt;/i&gt;method.&lt;/div&gt;&lt;pre&gt;Function.prototype.toString.call((3).constructor)&lt;/pre&gt;&lt;pre&gt;// "function Number() {
//    [native code]
// }"&lt;/pre&gt;&lt;div&gt;The method gives you the complete source of a function. In the case of native functions, it just says "[native code]" in the body. One could easily parse out the name of the function to figure out type of the object using this helper function&lt;/div&gt;&lt;pre&gt;function type(obj){
	var text = Function.prototype.toString.call(obj.constructor)
	return text.match(/function (.*)\(/)[1]
}&lt;/pre&gt;&lt;pre&gt;type("abc") // "String"&lt;/pre&gt;&lt;div&gt;This one will work for user-defined types too&lt;/div&gt;&lt;pre&gt;type(new Animal) // "Animal"&lt;/pre&gt;&lt;div&gt;this code has a problem wrt popup windows in IE just like &lt;i&gt;instanceof.&lt;/i&gt;&amp;nbsp;It's because when &lt;i&gt;Function.prototype.toString&lt;/i&gt;&amp;nbsp;is called with a constructor from another parallel universe, it can only discern the constructor as an object("[object Object]"), and thus rejects the argument and throws a "Function expected" error. This problem can actually be worked around by referencing the toString method indirectly&lt;/div&gt;&lt;pre&gt;&lt;span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', Verdana, Helvetica, Arial; font-size: 18px; white-space: normal; "&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;function type(obj){
	var text = obj.constructor.toString()
	return text.match(/function (.*)\(/)[1]
}&lt;/pre&gt;&lt;/span&gt;&lt;/pre&gt;&lt;div&gt;Now, it works for popup windows in IE too! This fix makes it susceptible to shadowing&lt;/div&gt;&lt;pre&gt;Array.toString = function(){ return "function NotArray(){ }" }&lt;/pre&gt;&lt;pre&gt;type([1,2,3]) // "NotArray"&lt;/pre&gt;&lt;div&gt;but still, I'd say this is pretty cool.&lt;/div&gt;&lt;div&gt;Now, let's return to user-defined types for a minute. With this approach, there's no way to distinguish between two different user-defined types with the same name&lt;/div&gt;&lt;pre&gt;var f = function Animal(){ "something" }&lt;br&gt;&lt;/pre&gt;&lt;pre&gt;var g = function Animal(){ "something entirely different" }&lt;br&gt;&lt;/pre&gt;&lt;pre&gt;type(new f) // "Animal"&lt;/pre&gt;&lt;pre&gt;type(new g) // "Animal"&lt;/pre&gt;&lt;div&gt;For this reason, this method is inferior to &lt;i&gt;instanceof&lt;/i&gt;&amp;nbsp;for user-defined types. Another seemingly obvious problem with this approach is performance, but I'd have to benchmark it(jsperf!) to make a real claim.&lt;/div&gt;&lt;h2&gt;DOM Elements and Host Objects&lt;/h2&gt;&lt;div&gt;So far, I have not mentioned type checking for DOM elements and host objects. That's because it's &lt;i&gt;hard&lt;/i&gt;. With the exception of duck-typing, none of the methods mentioned above will work for all browsers. If you drop IE7 and below, however, you can actually get some of the things to work. The output below were created using&amp;nbsp;&lt;a href="http://tutti.tobyho.com"&gt;Tutti&lt;/a&gt;&lt;/div&gt;&lt;pre&gt;&amp;gt; var div = document.createElement('div')
&amp;gt; typeof div
Safari 5.0 =&amp;gt; object
Firefox 3.6 =&amp;gt; object
IE 7.0 =&amp;gt; object
IE 8.0 =&amp;gt; object
Opera 11.01 =&amp;gt; object
&amp;gt; div instanceof Element
Safari 5.0 =&amp;gt; true
Firefox 3.6 =&amp;gt; true
IE 7.0 =&amp;gt; Error: 'Element' is undefined
IE 8.0 =&amp;gt; true
Opera 11.01 =&amp;gt; true
&amp;gt; div instanceof HTMLDivElement
Safari 5.0 =&amp;gt; true
Firefox 3.6 =&amp;gt; true
IE 8.0 =&amp;gt; true
IE 7.0 =&amp;gt; Error: 'HTMLDivElement' is undefined
Opera 11.01 =&amp;gt; true&lt;br&gt;&lt;/pre&gt;&lt;div&gt;First up, &lt;i&gt;typeof&lt;/i&gt; is useless, that was expected. Next, everyone but IE 7 recognizes that a div is an instance of&amp;nbsp;&lt;i&gt;Element&lt;/i&gt;&amp;nbsp;as well as an &lt;i&gt;HTMLDivElem&lt;/i&gt;ent&lt;i&gt;. &lt;/i&gt;In IE7, those constructors aren't even present. Next,&lt;/div&gt;&lt;pre&gt;&amp;gt; Object.prototype.toString.call(div)
Safari 5.0 =&amp;gt; [object HTMLDivElement]
Firefox 3.6 =&amp;gt; [object HTMLDivElement]
IE 7.0 =&amp;gt; [object Object]
IE 8.0 =&amp;gt; [object Object]
Opera 11.01 =&amp;gt; [object HTMLDivElement]&lt;br&gt;&lt;/pre&gt;&lt;div&gt;The result of &lt;i&gt;Object.prototype.toString&lt;/i&gt;&amp;nbsp;in IE - even IE 8 - is particularly &lt;i&gt;un&lt;/i&gt;helpful. What about&lt;/div&gt;&lt;pre&gt;&amp;gt; div.constructor.toString()
Safari 5.0 =&amp;gt; [object HTMLDivElementConstructor]
Firefox 3.6 =&amp;gt; [object HTMLDivElement]
IE 7.0 =&amp;gt; Error: 'div.constructor' is null or not an object
IE 8.0 =&amp;gt; [object HTMLDivElement]
Opera 11.01 =&amp;gt; function HTMLDivElement() { [native code] }&lt;br&gt;&lt;/pre&gt;&lt;div&gt;&lt;i&gt;Function.prototype.toString: &lt;/i&gt;it gives us something useful for IE8, but every browser has a slightly different output.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Fun! Try another one? Allllllllllllllllrrrighty then!&lt;/div&gt;&lt;pre&gt;&amp;gt; typeof window
Safari 5.0 =&amp;gt; object
Firefox 3.6 =&amp;gt; object
IE 8.0 =&amp;gt; object
IE 7.0 =&amp;gt; object
Opera 11.01 =&amp;gt; object
&amp;gt; window instanceof Window
Safari 5.0 =&amp;gt; ReferenceError: Can't find variable: Window
Firefox 3.6 =&amp;gt; true
IE 8.0 =&amp;gt; true
IE 7.0 =&amp;gt; Error: 'Window' is undefined
Opera 11.01 =&amp;gt; ReferenceError: Undefined variable: Window
&amp;gt; Object.prototype.toString.call(window)
Safari 5.0 =&amp;gt; [object DOMWindow]
Firefox 3.6 =&amp;gt; [object Object]
IE 8.0 =&amp;gt; [object Object]
IE 7.0 =&amp;gt; [object Object]
Opera 11.01 =&amp;gt; [object Window]
&amp;gt; window.constructor
Safari 5.0 =&amp;gt; function Object() {
    [native code]
}
Firefox 3.6 =&amp;gt; function Object() {
    [native code]
}
IE 8.0 =&amp;gt; [object Window]
IE 7.0 =&amp;gt; undefined
Opera 11.01 =&amp;gt; function Object() { [native code] }&lt;br&gt;&lt;/pre&gt;&lt;div&gt;With &lt;i&gt;window&lt;/i&gt; it is just &lt;i&gt;all&lt;/i&gt; over the place, none of these methods worked for all browsers. You can try testing out some other host objects if you want, but in general it doesn't look doable. However, in my testing, the XMLHttpRequest object and DOM and Text elements look doable using &lt;i&gt;instanceof&lt;/i&gt;, if you can drop support for IE7 and below.&lt;/div&gt;&lt;h2&gt;What We've Learned&lt;/h2&gt;&lt;div&gt;Checking types in Javascript is a big mess. Although it's really not that hard to check for any one particular type, it is definitely not consistent across types, and you probably have had to make a lot of choices along the way. So it helps to know about all the different options. In an upcoming post, I will try to make all of this easier with a small piece of code. Stay tuned.&lt;/div&gt;&lt;h2&gt;Sources&lt;/h2&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;&lt;a href="http://javascript.crockford.com/remedial.html"&gt;Remedial Javascript&lt;/a&gt;&amp;nbsp;by Crockford&lt;/li&gt;&lt;li&gt;&lt;a href="http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/"&gt;instanceof considered harmful&lt;/a&gt;&lt;br&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript"&gt;An SO question w some helpful info&lt;/a&gt;&lt;br&gt;&lt;/li&gt;&lt;li&gt;Crockford&amp;nbsp;&lt;a href="http://groups.google.com/group/comp.lang.javascript/msg/1afbcb0da1cd4aef"&gt;calling instanceof useless&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;</description>
      <pubDate>Fri, 28 Jan 2011 12:51:45 +0000</pubDate>
      <guid>http://wiki.futuretoby.com/Checking_Types_in_Javascript</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Checking_Types_in_Javascript</link>
    </item>
    <item>
      <title>Trampolines in Javascript and the Quest for Fewer Nested Callbacks</title>
      <description>The problem of Javascript coders often having to deal with more than the desired number of nested callback functions have never really went away.&amp;nbsp;&lt;a href="Continuation-Passing Style: Don't Overdo it"&gt;My complaint&lt;/a&gt;&amp;nbsp;has been stated&amp;nbsp;not long ago. Lately, with the raise of&amp;nbsp;&lt;a href="http://nodejs.org"&gt;node.js&lt;/a&gt;, the complaints seemed to have gotten louder, or just more&amp;nbsp;&lt;i&gt;numerous&lt;/i&gt;. At&amp;nbsp;&lt;a href="http://jsconf.eu/2010/"&gt;JSConf EU 2010&lt;/a&gt;, there were&amp;nbsp;&lt;a href="http://jsconf.eu/2010/speaker/dont_write_spaghetti_code_in_s.html"&gt;no&lt;/a&gt;&amp;nbsp;&lt;a href="http://jsconf.eu/2010/speaker/loopage_by_douglas_crockford.html"&gt;fewer&lt;/a&gt;&amp;nbsp;&lt;a href="http://jsconf.eu/2010/speaker/techniques_and_tools_for_tamin.html"&gt;than&lt;/a&gt;&amp;nbsp;&lt;a href="http://jsconf.eu/2010/speaker/techniques_for_a_single_stack.html"&gt;5&lt;/a&gt;&amp;nbsp;&lt;a href="http://jsconf.eu/2010/speaker/getting_functional_with_fab.html"&gt;talks&lt;/a&gt;&amp;nbsp;addressing this issue, each in their own unique way.&amp;nbsp;&lt;div&gt;&lt;br&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;Crockford himself, for example, thinks that this is just the way it should be, and people who don't like it are just grumpy (Waa!)&lt;br&gt;&lt;/li&gt;&lt;li&gt;Ryan Dahl glossed over the problem of losing the stack, and suggested that you just roll your own solution for remembering state across your series of function contexts.&lt;/li&gt;&lt;li&gt;Jed Schmidt revealed his fantastic hack: program in continuables/streams. The solution is actually very close to Haskell's I/O Monad, and is both clever and beautiful, but it requires you to change your mind-set completely and therefore is unlikely to gain a lot of mindshare.&lt;/li&gt;&lt;li&gt;Tim Caswell introduced a helper library called &lt;i&gt;Step&lt;/i&gt; which allows you to chain your functions rather than nest them.&lt;/li&gt;&lt;li&gt;Tom Hughes-Croucher recommended using named functions, for the stacktraces will display them names and therefore be more helpful.&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;More recently, Kyle Simpson(Getify) started a twitter thread and&amp;nbsp;&lt;a href="http://blog.getify.com/2010/12/native-javascript-sync-async/"&gt;blog post&lt;/a&gt;&amp;nbsp;with his own proposed addition to the language, which boils down to an @ operator that cooperates with dojo-style promises.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Clearly, we are far from reaching&amp;nbsp;consensus.&lt;/div&gt;&lt;/div&gt;&lt;h2&gt;Generators&lt;/h2&gt;&lt;div&gt;One thing that was brought up over and over again in&amp;nbsp;&lt;a href="http://www.mail-archive.com/es-discuss%40mozilla.org/msg05317.html"&gt;Kyle's thread&lt;/a&gt;&amp;nbsp;is generators. My take is this: generators have existed in Spidermonkey ever since Firefox 2, so if you are open to new language features, generators have already been around the block, we just have to get it into the standard, at which point I believe node.js - and just Javascript programmers in general - can really benefit.&amp;nbsp;I have long been using generators in Python, so I know that they are very powerful. All of this motivated me to go deeper and see how far it can go in the&lt;i&gt;&amp;nbsp;Quest for Fewer Nested Callbacks&lt;/i&gt;.&lt;/div&gt;&lt;h3&gt;First, the Punchline!&lt;/h3&gt;&lt;div&gt;Let's see the punchline now because it may take a while before we can get through all the steps necessary to arrive at it: with the help of generators and a bit of support code, this(code taken directly from Kyle's post)&lt;/div&gt;&lt;pre&gt;setTimeout(function(){
   xhr("/something.ajax?greeting", function(greeting) {
      xhr("/else.ajax?who&amp;amp;greeting="+greeting, function(who) {
         console.log(greeting+" "+who);
      });
   });
}, 1000);&lt;br&gt;&lt;/pre&gt;&lt;div&gt;can be written as&lt;/div&gt;&lt;pre&gt;&lt;meta charset="utf-8"&gt;yield sleep(1000)
var greeting = yield xhr('/something.ajax?greeting')
var who = yield xhr('/else.ajax?who&amp;amp;greeting=' + greeting)
console.log(greeting + ' ' + who)&lt;br&gt;&lt;/pre&gt;&lt;div&gt;The supporting function&lt;/div&gt;&lt;pre&gt;function xhr(url, callback) {
   var x = new XMLHttpRequest();
   x.onreadystatechange = function(){
      if (x.readyState == 4) {
         callback(x.responseText);
      }
   };
   x.open("GET",url);
   x.send();
}&lt;br&gt;&lt;/pre&gt;&lt;div&gt;almost remains unchanged, all it needs is to be wrapped like so&lt;/div&gt;&lt;pre&gt;&lt;meta charset="utf-8"&gt;&lt;span class="Apple-style-span" style="white-space: normal; font-size: 18px; font-family: Georgia, 'Times New Roman', Verdana, Helvetica, Arial; "&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;function _xhr(url, callback) {
   var x = new XMLHttpRequest();
   x.onreadystatechange = function(){
      if (x.readyState == 4) {
         callback(x.responseText);
      }
   };
   x.open("GET",url);
   x.send();
}&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;function xhr(url){&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;   _xhr(url, (yield Continuation))&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;   yield Suspend&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;}&lt;/pre&gt;&lt;/span&gt;&lt;/pre&gt;&lt;div&gt;and, sleep() is implemented as&lt;/div&gt;&lt;pre&gt;function sleep(ms){
    setTimeout((yield Continuation), ms)
    yield Suspend
}&lt;br&gt;&lt;/pre&gt;&lt;div&gt;Are you&amp;nbsp;intrigued? Read on, then.&lt;/div&gt;&lt;h3&gt;Gentle Introduction to Generators&lt;br&gt;&lt;/h3&gt;&lt;div&gt;&lt;i&gt;What are generators? How do they work? How can I use them?&lt;/i&gt;&lt;/div&gt;&lt;div&gt;Let's start with&lt;i&gt;&amp;nbsp;"How can I use them?"&lt;/i&gt;. You have to be running Firefox 2 or above, or alternatively you can download Spidermonkey by itself.&lt;/div&gt;&lt;div&gt;For my code samples I'll assume you are using Firefox.&lt;/div&gt;&lt;div&gt;Next, you have to use&amp;nbsp;type="application/javascript;version=1.7" in your script tag. I guess Mozilla was sheepish about this feature when they released it, given that it introduced a new keyword.&lt;/div&gt;&lt;div&gt;So, a hello world example for generators would be:&lt;/div&gt;&lt;pre&gt;&amp;lt;script type="application/javascript;version=1.7"&amp;gt;
// This is a generator function
function naturalNumbers(){
    var i = 0
    while (true){
        yield i++
    }
}
var N = naturalNumbers() // N is now a generator
console.log(N.next()) // prints 0
console.log(N.next()) // prints 1
console.log(N.next()) // prints 2
// and so forth
&amp;lt;/script&amp;gt;&lt;br&gt;&lt;/pre&gt;&lt;div&gt;&lt;font class="Apple-style-span" size="4"&gt;First things first, a generator function is not the same as a function. Repeat after me: &lt;i&gt;a generator function is not a function&lt;/i&gt;. Within a generator function, you have &lt;i&gt;yield&lt;/i&gt; statements; within a function, you have &lt;i&gt;return&lt;/i&gt; statements - you &lt;i&gt;cannot&lt;/i&gt; have both.&lt;/font&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="font-size: large; "&gt;The generator object has a few methods, here we are only demonstrating next() - which executes the code within the generator function until a &lt;/span&gt;&lt;span class="Apple-style-span" style="font-size: large; "&gt;&lt;i&gt;yield&lt;/i&gt;&lt;/span&gt;&lt;span class="Apple-style-span" style="font-size: large; "&gt;&amp;nbsp;statement is reached, and returns the value being yielded. If you call next() on it again, it will continue from where it left off, and once again execute till the next yield&lt;/span&gt;&lt;span class="Apple-style-span" style="font-size: large; "&gt;&amp;nbsp;is reached. In our natural numbers example, since we are yielding the counter within an infinite loop, we can keep calling next() on the generator object to get the next number forever...&lt;/span&gt;&lt;/div&gt;&lt;h3&gt;Receiving Values&lt;/h3&gt;&lt;div&gt;It turns out that in addition to &lt;i&gt;yielding&lt;/i&gt; values,&amp;nbsp;the yield statement can also &lt;i&gt;receive&lt;/i&gt; values(proud of myself that I avoided using the word&lt;i&gt;&amp;nbsp;&lt;/i&gt;"return"&amp;nbsp;in this sentence).&lt;/div&gt;&lt;div&gt;For a yield statement to receive a value, the holder of the generator must call the send() method with a value instead of the next() function&lt;/div&gt;&lt;pre&gt;function makePrinter(){
    while(true){
        var message = (yield)
        console.log(message)
    }
}
var printer = makePrinter()
printer.next() // You may not send a value to a newly created generator
printer.send('Hello')
printer.send('I am sending this message')
printer.send('into the generator')
printer.send('and it be received and get printed')&lt;br&gt;&lt;/pre&gt;&lt;div&gt;Here we created a printer generator whose job is only to print the objects that it receives from the &lt;i&gt;yields&lt;/i&gt;.&amp;nbsp;You can't send in a value for the first invocation of the generator because it hasn't had a chance to yield yet, but after that, you can send as many as you want, since it yields infinite times.&lt;/div&gt;&lt;div&gt;As you can see, we are switching back and forth between two separate threads of execution(but not Threads ;).&lt;/div&gt;&lt;h3&gt;Trampolining&lt;/h3&gt;&lt;div&gt;Now that you understand generators, the next step is to put it together to get rid of our nested callbacks. To do that, we need to know a technique called trampolining. Neil Mix's&amp;nbsp;&lt;a href="http://www.neilmix.com/2007/02/07/threading-in-javascript-17/"&gt;article&lt;/a&gt;&amp;nbsp;has some brilliant code that shows you how to do it in Javascript, but it was David Beazley's&amp;nbsp;&lt;a href="http://www.dabeaz.com/coroutines/trampoline.py"&gt;gentle example in Python&lt;/a&gt;&amp;nbsp;that helped me understand what's going on.&lt;/div&gt;&lt;div&gt;Let me translate his code to Javascript, and put in some comments for ya&lt;/div&gt;&lt;pre&gt;function add(x,y){
    yield x + y             // yield the result of addition
}
function main(){
    var r = yield add(2,2)      // yield the result of add(2,2): a generator
    console.log(r)&lt;/pre&gt;&lt;pre&gt;    yield
}
function run(){
    var m = main()&lt;/pre&gt;&lt;pre&gt;    var sub = m.next()&amp;nbsp;     // start the code execution in main()&lt;/pre&gt;&lt;meta charset="utf-8"&gt;&lt;pre&gt;                             // sub is now generator from calling add()&lt;/pre&gt;&lt;pre&gt;    var result = sub.next() // start execution of sub&lt;/pre&gt;&lt;pre&gt;                             // result now has the value of 2 + 2: 4
    m.send(result)           // send back to generator
}
run()&lt;br&gt;&lt;/pre&gt;&lt;div&gt;The main feature of trampolining is that a value yielded by a generator is yet another generator, such is the case on this line&lt;/div&gt;&lt;pre&gt;&lt;meta charset="utf-8"&gt;&lt;span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', Verdana, Helvetica, Arial; font-size: 18px; white-space: normal; "&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;var r = yield add(2,2)      // yield the result of add(2,2): a generator&lt;/pre&gt;&lt;/span&gt;&lt;meta charset="utf-8"&gt;&lt;/pre&gt;&lt;div&gt;In this example the thread of execution is bouncing between 3 different contexts, namely the run() function and the add() and main() generator functions. We started within run(), bounced to main(), then back to run(), then to add(), then back to run(), then back to main() again, and then finally exiting in run() again.&lt;/div&gt;&lt;div&gt;Here's a picture so we can visualize what's happening&lt;/div&gt;&lt;div&gt;&lt;img title="Trampoline Example" alt="Trampoline Example" src="http://lh3.ggpht.com/_1m4jxPGXQAo/TQLjLF94AEI/AAAAAAAAREw/teMTn0UstOU/s800/Screen%20shot%202010-12-10%20at%209.33.58%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;But, right now the run() function is inflexible. We can generalize it to handle arbitrary levels of nested generator execution - with a stack&lt;/div&gt;&lt;pre&gt;function run(gen){
    // is object a generator?
    function isGenerator(obj){
        return String(obj) === '[object Generator]'
    }
    // last element of array
    function last(arr){
        return arr[arr.length - 1]
    }
    var stack = []
    var retval = gen
    try{
        while (true){
            if (isGenerator(retval)){   // if a generator
                stack.push(retval)      // push it onto the stack
                retval = undefined
            }else{
                stack.pop().close()     // if we got a normal value
                                        // pop the stack and
            }
            gen = last(stack)           // get the generator at top of the stack
            if (!gen) break
            retval = gen.send(retval)   // send retval to the generator
                                        // if retval is undefined, it acts just
                                        // like next()
        }
    }catch(e if e === StopIteration){
        console.log('Program ended.')
    }
}&lt;br&gt;&lt;/pre&gt;&lt;div&gt;We have a stack which starts out containing the generator from which we are starting execution - &lt;i&gt;gen&lt;/i&gt;. Then, we keep on executing the generator at the top of the stack. If the received value is also a generator, we push it onto the stack and keep going; if we receive a normal value, then we pop the generator off the stack and, on the next iteration of the loop - send the value to previous generator one level down in the stack.&lt;/div&gt;&lt;div&gt;To call the new and improved the run() function you pass it the entry level generator like so&lt;/div&gt;&lt;pre&gt;run(main())&lt;/pre&gt;&lt;div&gt;Let's take the same example again, but executing with the generic run() function instead. This time, let's visualize it as a stack. First we start with main() at the bottom&lt;/div&gt;&lt;div&gt;&lt;img title="1-level stack" alt="1-level stack" src="http://lh5.ggpht.com/_1m4jxPGXQAo/TQLm38LvegI/AAAAAAAARFE/PFMe3FhcdHY/s800/Screen%20shot%202010-12-10%20at%209.49.22%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;next,&lt;/div&gt;&lt;pre&gt;var r = yield add(2,2)&lt;br&gt;&lt;/pre&gt;&lt;meta charset="utf-8"&gt;&lt;div&gt;add(2, 2) is pushed onto the stack, because it is a generator. The parameters x and y are both assigned to 2 inside the scope and also go on the stack.&lt;/div&gt;&lt;div&gt;&lt;img title="2-level Stack" alt="2-level Stack" src="http://lh4.ggpht.com/_1m4jxPGXQAo/TQO3OpBCjAI/AAAAAAAARGg/CL2-b1YQp8M/s800/Screen%20shot%202010-12-11%20at%2012.38.36%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;add() then executes and&amp;nbsp;&lt;/div&gt;&lt;pre&gt;yield x + y&lt;/pre&gt;&lt;div&gt;yields a numerical value: 4. Because, this is not a generator, we pop() the stack, then send the 4 back to main()&lt;/div&gt;&lt;pre&gt;&lt;meta charset="utf-8"&gt;&lt;span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', Verdana, Helvetica, Arial; font-size: 18px; white-space: normal; "&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;var r = yield add(2,2)&lt;/pre&gt;&lt;/span&gt;&lt;/pre&gt;&lt;div&gt;where 4 is assigned to &lt;i&gt;r&lt;/i&gt;.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;img title="1-level stack again" alt="1-level stack again" src="http://lh4.ggpht.com/_1m4jxPGXQAo/TQLoTls3hmI/AAAAAAAARFc/ixOdUkSDMC0/s800/Screen%20shot%202010-12-10%20at%209.55.59%20PM.jpg"&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;main() then prints the value via console.log and then&lt;/div&gt;&lt;pre&gt;yield&lt;/pre&gt;&lt;div&gt;again, which ends the execution.&lt;/div&gt;&lt;h3&gt;Wait, I've Seen That Before!&lt;/h3&gt;&lt;div&gt;This... stack, it looks almost like... &lt;i&gt;an&amp;nbsp;execution stack&lt;/i&gt;! The interpreter maintains a stack when it's executing code and handling the execution of function calls - &lt;i&gt;and we've just reimplemented it using generators.&lt;/i&gt;&lt;/div&gt;&lt;div&gt;To see it another way, the only difference between the trampoline style code and normal functional code is the use of the yield statements. If you take out the yields - and substitute&amp;nbsp;&lt;i&gt;return&lt;/i&gt;&amp;nbsp;when appropriate, you'd have&lt;/div&gt;&lt;pre&gt;&lt;meta charset="utf-8"&gt;&lt;span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', Verdana, Helvetica, Arial; font-size: 18px; white-space: normal; "&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;function add(x,y){
    return x + y
}
function main(){
    var r = add(2,2)      // yield the result of add(2,2): a generator
    console.log(r)&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;    return
}&lt;/pre&gt;&lt;/span&gt;&lt;/pre&gt;&lt;div&gt;Now that we have a generalized run() function that handles the stack generically, we can handle recursion&lt;/div&gt;&lt;pre&gt;// the Fibonacci sequence using recursion - don't try this at home!&lt;/pre&gt;&lt;pre&gt;function fib(n){
    if (n == 1 || n == 2)
        yield 1
    else
        yield (yield fib(n-1)) + (yield fib(n-2))
}&lt;/pre&gt;&lt;pre&gt;function main(){
    console.log(yield fib(10))
}&lt;br&gt;&lt;/pre&gt;&lt;div&gt;This actually works!&lt;/div&gt;&lt;h3&gt;Wrapping Asynchronous Execution&lt;/h3&gt;&lt;div&gt;Okay, that's all fine and good, but we still haven't address the problem of making asynchronous code less onerous. In order to tackle that problem, we need to do a little bit more.&lt;/div&gt;&lt;div&gt;By keeping a stack of all of the generators we have in progress, we can restart them back at any time. However, we need to be able to suspend the execution of a generator if we are waiting for an asynchronous response. We also need to pass a function as the callback handler for the async function call, &lt;i&gt;only&lt;/i&gt; by which can we know when to resume execution of the thread.&lt;/div&gt;&lt;div&gt;The solution is demonstrated by the implementation of sleep()&lt;/div&gt;&lt;pre&gt;function sleep(millis) {
    setTimeout((yield Continuation), millis)
    yield Suspend
}&lt;br&gt;&lt;/pre&gt;&lt;div&gt;&lt;i&gt;Continuation&lt;/i&gt; and &lt;i&gt;Suspend&lt;/i&gt;&amp;nbsp;are special constants - that we created - used as signals to run().&lt;/div&gt;&lt;div&gt;Here's how this works:&lt;/div&gt;&lt;pre&gt;&lt;meta charset="utf-8"&gt;&lt;span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', Verdana, Helvetica, Arial; font-size: 18px; white-space: normal; "&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;(yield Continuation)&lt;/pre&gt;&lt;/span&gt;&lt;/pre&gt;&lt;div&gt;will receive a function as a callback handler to setTimeout. Let's call this function the &lt;i&gt;continuation&lt;/i&gt;.&lt;/div&gt;&lt;pre&gt;&lt;meta charset="utf-8"&gt;&lt;span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', Verdana, Helvetica, Arial; font-size: 18px; white-space: normal; "&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;yield Suspend&lt;/pre&gt;&lt;/span&gt;&lt;/pre&gt;&lt;div&gt;will suspend the execution of this generator, and therefore also suspending this thread of execution until the continuation has been called by setTimeout(). When the continuation eventually gets called, it will resume execution of this generator, which starts back up again after the line&lt;/div&gt;&lt;pre&gt;&lt;meta charset="utf-8"&gt;&lt;span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', Verdana, Helvetica, Arial; font-size: 18px; white-space: normal; "&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;yield Suspend&lt;/pre&gt;&lt;/span&gt;&lt;/pre&gt;&lt;div&gt;Our new run() function that handles all of this looks like&lt;/div&gt;&lt;pre&gt;function run(gen){
    function isGenerator(obj){
        return String(obj) === '[object Generator]'
    }
    function last(arr){
        return arr[arr.length - 1]
    }
    function startBouncing(retval){
        try{
            while (true){
                if (isGenerator(retval)){
                    stack.push(retval)
                    retval = undefined
                }else if (retval === Suspend){
                    break                       // to suspend execution:
                                                // just break out of this
                                                // while-loop.
                                                // we can later resume
                                                // by re-starting another
                                                // while-loop by calling
                                                // startBouncing() again
                }else if (retval === Continuation){
                    retval = startBouncing      // send startBouncing
                                                // back as the callback
                                                // handler to the async
                                                // function call
                }else{
                    stack.pop().close()
                }
                gen = last(stack)
                if (!gen) break
                retval = gen.send(retval)
            }
        }catch(e if e === StopIteration){
            console.log('Program ended.')
        }
    }    
    var stack = []
    var retval
    startBouncing(gen)
}&lt;br&gt;&lt;/pre&gt;&lt;div&gt;We've refactored the while-loop inside of a function: startBouncing(). When we need to suspend, we just break out of the while-loop. When we need to resume, we just call startBouncing() to start the while-loop all over again. All the while we still have the stack in tact. The callback handler we send as the continuation is none other than the startBouncing() function. Notice that startBouncing() also takes a retval as argument. This enables us to send the first argument of the callback back to the generator, as the XHR example shows&lt;/div&gt;&lt;pre&gt;function _xhr(url, callback){
    var xhr = new XMLHttpRequest()
    xhr.open('GET', url)
    xhr.onreadystatechange = function(){
        if (this.readyState == 4){&lt;/pre&gt;&lt;pre&gt;            // send the responseText as the first arg of the continuation
            callback(this.responseText)
        }
    }
    xhr.send()
}
function xhr(url){
    _xhr(url, (yield Continuation))
    yield Suspend
}&lt;br&gt;&lt;/pre&gt;&lt;div&gt;Because we are passing the responseText as the first argument to the callback(the continuation) - by our made up convention - it will be the value that's sent back to the caller of this generator function. So&lt;/div&gt;&lt;pre&gt;var responseText = yield xhr('/something.ajax')&lt;/pre&gt;&lt;div&gt;Just works!&lt;/div&gt;&lt;h3&gt;Adding Back Exceptions&lt;/h3&gt;&lt;div&gt;Async-style calls don't really throw any exceptions. That's because if there &lt;i&gt;were&lt;/i&gt;&amp;nbsp;problems with the request, you &lt;i&gt;could&lt;/i&gt; only be notified asynchronously - the original execution has already past! However, now that we have something that looks like synchronous code again, we can put exceptions back into play. We will use the convention that if an instance of Error is passed as the first argument of the continuation, then we will throw it. Thus for our xhr function&lt;/div&gt;&lt;pre&gt;function _xhr(url, callback){
    var xhr = new XMLHttpRequest()
    xhr.open('GET', url)
    xhr.onreadystatechange = function(){
        if (this.readyState == 4){
            if (this.status === 200)
                callback(this.responseText)
            else{
                var ex = new Error("XMLHttpRequest Error: " + 
                    this.statusText + ': ' + this.status)&lt;/pre&gt;&lt;pre&gt;                // pass in an error object to the continuable to throw it
                callback(ex)
            }
        }
    }
    xhr.send()
}&lt;br&gt;&lt;/pre&gt;&lt;div&gt;To throw an exception from within a generator you actually have to call the throw() method on the generator object. We just need to add an extra else-if inside of our big if statement inside of the while-loop in run()&lt;/div&gt;&lt;pre&gt;else if (retval instanceof Error){
    stack.pop().close()
    last(stack).throw(retval)&lt;/pre&gt;&lt;pre&gt;}&lt;br&gt;&lt;/pre&gt;&lt;div&gt;Now we can get exceptions throw from the xhr() generator function&lt;/div&gt;&lt;pre&gt;function main(){
    try{
        var result = yield xhr('/doesnotexist.ajax')
        console.log('blah')
    }catch(e){
        console.log('exception caught: ' + e)
    }
}&lt;br&gt;&lt;/pre&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;div&gt;I think the trampolining technique is very compelling, perhaps even more compelling than the continuables in fab.js. The only thing we need is support for generators in more engines. As far as I know, Spidermonkey and Rhino are the only 2 that support it right now.&lt;/div&gt;&lt;h2&gt;Source Code&lt;/h2&gt;&lt;div&gt;You can download all of the&amp;nbsp;&lt;a href="https://github.com/airportyh/trampoline.js"&gt;code examples&lt;/a&gt;&amp;nbsp;shown in this post.&lt;/div&gt;&lt;meta charset="utf-8"&gt;&lt;h2&gt;References&lt;br&gt;&lt;meta charset="utf-8"&gt;&lt;/h2&gt;&lt;div&gt;&lt;ol&gt;&lt;li&gt;&lt;a href="http://www.dabeaz.com/coroutines/index.html"&gt;&amp;nbsp;A Curious Course on Coroutines and Concurrency&lt;/a&gt;&amp;nbsp;brilliant tutorial on generators by David Beazley&lt;br&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="https://developer.mozilla.org/en/New_in_JavaScript_1.7"&gt;Introduction to Generators and Iterators in JavaScript 1.7&lt;/a&gt;&amp;nbsp;- from MDN&lt;br&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://www.neilmix.com/2007/02/07/threading-in-javascript-17/"&gt;Threading in JavaScript 1.7&lt;/a&gt;&amp;nbsp;by Neil Mix&lt;br&gt;&lt;/li&gt;&lt;/ol&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;</description>
      <pubDate>Fri, 10 Dec 2010 14:32:43 +0000</pubDate>
      <guid>http://wiki.futuretoby.com/Trampolines_in_Javascript_and_the_Quest_for_Fewer_Nested_Callbacks</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Trampolines_in_Javascript_and_the_Quest_for_Fewer_Nested_Callbacks</link>
    </item>
    <item>
      <title>Tutti - Multiple Browser Interactive Javascript Shell</title>
      <description>&lt;div&gt;&lt;i&gt;Cough, cough...&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;&lt;br&gt;&lt;/i&gt;&lt;/div&gt;Have you ever wished that the Firebug console or &lt;i&gt;&amp;lt;insert your favorite Javascript Shell&amp;gt;&lt;/i&gt; could execute the piece of Javascript you typed in on IE, or maybe some other browsers as well - &lt;i&gt;at the same time?&lt;/i&gt;&lt;div&gt;&lt;br&gt;&lt;div&gt;&lt;i&gt;Well, now you can!&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;&lt;br&gt;&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;Now&lt;/i&gt;&amp;nbsp;there's&amp;nbsp;&lt;a href="http://tuttijs.com"&gt;Tutti&lt;/a&gt;&amp;nbsp;- a Javascript Shell that will lets you execute Javascript on multiple browsers - &lt;i&gt;all at the same time!&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;&lt;br&gt;&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;&lt;/i&gt;Here's how it works: to get started,&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;ol&gt;&lt;li&gt;Open&amp;nbsp;&lt;a href="http://tuttijs.com"&gt;tuttijs.com&lt;/a&gt;&amp;nbsp;in your browser&lt;/li&gt;&lt;li&gt;Create a new room &lt;i&gt;(click)&lt;/i&gt;.&lt;/li&gt;&lt;li&gt;Copy-n-paste the URL from your current browser window to another browser of your choice, say, IE 8.&lt;/li&gt;&lt;li&gt;Repeat step two for each browser you you want to test.&lt;/li&gt;&lt;li&gt;Type in some Javascript, hit ENTER, and see them results from all your browsers!&lt;/li&gt;&lt;/ol&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Tutti uses&amp;nbsp;&lt;a href="http://socket.io/"&gt;Socket.IO&lt;/a&gt;,&amp;nbsp;&lt;a href="http://nodejs.org/"&gt;node.js&lt;/a&gt;, and&amp;nbsp;&lt;a href="http://en.wikipedia.org/wiki/WebSockets"&gt;WebSocket&lt;/a&gt;&amp;nbsp;technology - &lt;i&gt;it's so just cloud&#8482;&lt;/i&gt;!&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Tutti supports on all major browsers, including&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;Firefox 3.6 and 4&lt;br&gt;&lt;/li&gt;&lt;li&gt;Chrome 8.0&lt;br&gt;&lt;/li&gt;&lt;li&gt;Safari 5.0&lt;br&gt;&lt;/li&gt;&lt;li&gt;Safari 4 Mobile for iPad&lt;br&gt;&lt;/li&gt;&lt;li&gt;Opera 10&lt;br&gt;&lt;/li&gt;&lt;li&gt;Internet Explorer 6, 7, and 8&lt;br&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Tutti is open source, but &lt;i&gt;that's not all&lt;/i&gt;, it's also&amp;nbsp;&lt;a href="http://github.com/airportyh/tutti"&gt;hosted on GitHub&lt;/a&gt;&amp;nbsp;so you can download it and run it on your own machine, or better yet: &lt;i&gt;fork it&lt;/i&gt; and hack on it to your heart's content!&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Try it &lt;i&gt;now!&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;To try it go to&amp;nbsp;&lt;/i&gt;&lt;a href="http://tuttijs.com"&gt;tuttijs.com&lt;/a&gt;&lt;i&gt;, or get the source at&amp;nbsp;&lt;/i&gt;&lt;i&gt;&lt;a href="http://github.com/airportyh/tutti"&gt;http://github.com/airportyh/tutti&lt;/a&gt;.&amp;nbsp;Remember dependencies such as Socket.IO-node, ExpressJS, node.js are installed separately.&lt;/i&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;&lt;br&gt;&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;Update: I've changed the domain to tuttijs.com. The old domain is still accessible though.&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;&lt;br&gt;&lt;/i&gt;&lt;/div&gt;&lt;/div&gt;</description>
      <pubDate>Thu, 09 Dec 2010 14:42:43 +0000</pubDate>
      <guid>http://wiki.futuretoby.com/Tutti_-_Multiple_Browser_Interactive_Javascript_Shell</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Tutti_-_Multiple_Browser_Interactive_Javascript_Shell</link>
    </item>
    <item>
      <title>Two Strategies for Avoiding Tedious Null-Checks</title>
      <description>&lt;div&gt;&lt;p&gt;Programmers have been plagued by having to write numerous checks for null values ever since the &lt;em&gt;dawn of time&lt;/em&gt;. Consider this example,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var customer = database.get(id)
var customerLastName = customer.name.last
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What if I told you that, any of &lt;code&gt;customer&lt;/code&gt;, &lt;code&gt;customer.name&lt;/code&gt;, and &lt;code&gt;customer.name.last&lt;/code&gt; could be &lt;code&gt;null&lt;/code&gt; at runtime? And if any of them are &lt;code&gt;null&lt;/code&gt; just set &lt;code&gt;customerLastName&lt;/code&gt; to &lt;code&gt;"Unknown"&lt;/code&gt;. You&#8217;d probably do something like&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var customerLastName = "Unknown"
var customer = database.get(id)
if (customer &amp;amp;&amp;amp; customer.name &amp;amp;&amp;amp; customer.name.last){
    customerLastName = customer.name.last
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is an awful lot of repetitive code, and you really don&#8217;t want to be writing it over and over again. But, what&#8217;s worse than having to write it, is actually having to read it later on.&lt;/p&gt;

&lt;p&gt;To see the amount of repetition in the above code, let&#8217;s break down the word frequency. The top repeated words are&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;customer&lt;/code&gt;: 5&lt;/li&gt;
&lt;li&gt;&lt;code&gt;name&lt;/code&gt;: 3&lt;/li&gt;
&lt;li&gt;&lt;code&gt;last&lt;/code&gt;: 2&lt;/li&gt;
&lt;li&gt;&lt;code&gt;customerLastName&lt;/code&gt;: 2&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you count phrases too,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;customer.name&lt;/code&gt;: 3&lt;/li&gt;
&lt;li&gt;&lt;code&gt;customer.name.last&lt;/code&gt;: 2&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There are actually &lt;a href="http://weblog.raganwald.com/2008/01/objectandand-objectme-in-ruby.html"&gt;numerous&lt;/a&gt; &lt;a href="http://ozmm.org/posts/try.html"&gt;hacks&lt;/a&gt; &lt;a href="http://weavejester.com/node/10"&gt;out&lt;/a&gt; &lt;a href="http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator%28%3F.%29"&gt;there&lt;/a&gt; already dedicated to solving this problem for ruby, groovy, and other various programming languages.&lt;/p&gt;

&lt;p&gt;In this post, I am going to investigate two approaches to tackling this in Javascript.&lt;/p&gt;

&lt;h2&gt;Approach 1&lt;/h2&gt;

&lt;p&gt;Because &lt;code&gt;null&lt;/code&gt; isn&#8217;t an object in Javascript, approaches like &lt;a href="http://weblog.raganwald.com/2008/01/objectandand-objectme-in-ruby.html"&gt;andand&lt;/a&gt; won&#8217;t work. So, what do we do when we want to extend something but can&#8217;t modify it? Right! We wrap it! This approach is called &lt;em&gt;NullSafe&lt;/em&gt;. Basically, like jQuery, you wrap the object you want to &lt;em&gt;query&lt;/em&gt;, and then chain method calls to it until you get the result you are looking for. At the end, you have to unwrap it to get the computed value. What I came up with is this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var customer = database.get(id)
var customerLastName = NullSafe(customer)._('name')._('last').val() || "Unknown"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Actually, I made it a little more powerful than that, even. In addition to getting an object&#8217;s properties, you can also call methods:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var customerLastName = NullSafe(database).$('get', id)._('name')._('last').val() || "Unknown"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then I added just a bit more convenience with the variable length arguments for getting a chain of properties:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var customerLastName = NullSafe(database).$('get', id)._('name', 'last').val() || "Unknown"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;How is this? Is this good? The syntax takes a little getting used to, but the advantage is that you only have write each thing just once, rather than the big repetitive mess you saw above. Also, chaining allows you to write everything in one line.&lt;/p&gt;

&lt;p&gt;The implementation of &lt;code&gt;NullSafe&lt;/code&gt; is pretty simple too, all but 30-plus LOC,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function NullSafe(obj){
    function NullSafe(obj){
        this.obj = obj
    }
    Wrapper = NullSafe
    var proto = Wrapper.prototype
    proto.call = proto.$ = function(){
        var name = arguments[0]
        var args = Array.prototype.slice.call(arguments, 1)
        var obj = null
        if (this.obj){
            var func = this.obj[name]
            if (this.obj &amp;amp;&amp;amp; func){
                obj = func.apply(this.obj, args)
            }
        }
        return new Wrapper(obj)
    }
    proto.get = proto._ = function(){
        var curr = this.obj
        for (var i = 0; i &amp;lt; arguments.length; i++){
            if (curr != null){
                curr = curr[arguments[i]]
            }
        }
        return new Wrapper(curr)
    }
    proto.val = function(){
        return this.obj
    }
    proto.toString = function(){
        return String(this.obj)
    }
    return new Wrapper(obj || this)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But then you might wonder why in the world I didn&#8217;t just use a &lt;code&gt;try&lt;/code&gt;-&lt;code&gt;catch&lt;/code&gt; block?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var customerLastName = "Unknown"
try{
    customerLastName = database.get(id).name.last
}catch(e){}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Approach 2&lt;/h2&gt;

&lt;p&gt;As you saw, the &lt;code&gt;try&lt;/code&gt;-&lt;code&gt;catch&lt;/code&gt; approach isn&#8217;t so bad. It is a bit verbose, and spans multiple lines, but we can fix that. &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var customerLastName = $try(function(){return database.get(id).name.last}) || "Unknown"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Pretty nice! Although the actually code is slightly longer than &lt;em&gt;NullSafe&lt;/em&gt;, this is easier to understand because within the inline function you are just writing what you would have normally written anyway if you hadn&#8217;t had to do the null checks. &lt;/p&gt;

&lt;p&gt;The implementation is even simpler,&lt;/p&gt;

&lt;pre id="scroll_to_here"&gt;&lt;code&gt;function $try(func){
    try{
        return func()
    }catch(e){
        return null
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Performance&lt;/h2&gt;

&lt;p&gt;I normally don't prematurely optimize, but with jsperf.com, I thought I&#8217;d be fun to compare. Intuitively, &lt;code&gt;$try&lt;/code&gt; should be faster because it&#8217;s doing less, but then again, exception handling &lt;em&gt;can&lt;/em&gt; be slow.&lt;/p&gt;

&lt;p&gt;I created two separate tests, one in which the chain would &lt;em&gt;have&lt;/em&gt; values &lt;a href="http://jsperf.com/2-approachs-to-avoid-null-checks-a"&gt;all the way through to the end&lt;/a&gt;, and another in which it would null-out early.&lt;/p&gt;

&lt;h3&gt;Results&lt;/h3&gt;

&lt;p&gt;The results were - drum roll please - &lt;code&gt;$try&lt;/code&gt; was significantly faster in almost all browsers, the only exceptions where is the &lt;em&gt;null-out early&lt;/em&gt; case for Chrome and Firefox, where it was only slightly slower - 20% - 40%. But in all the other cases, &lt;code&gt;$try&lt;/code&gt; was faster, in some cases, much faster - almost 7 times in Safari.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;With that, I will conclude that &lt;code&gt;$try&lt;/code&gt; is my preferred approach, given that it is easier to implement, produces easier to understand code, and executes faster that &lt;code&gt;NullSafe&lt;/code&gt;.&amp;nbsp;&lt;/p&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;</description>
      <pubDate>Tue, 30 Nov 2010 13:48:14 +0000</pubDate>
      <guid>http://wiki.futuretoby.com/Two_Strategies_for_Avoiding_Tedious_Null-Checks</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Two_Strategies_for_Avoiding_Tedious_Null-Checks</link>
    </item>
  </channel>
</rss>
