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

<channel>
	<title>unitstep.net &#187; JavaScript</title>
	<atom:link href="http://unitstep.net/blog/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://unitstep.net</link>
	<description>the home of peter chng</description>
	<pubDate>Sun, 05 Oct 2008 17:42:16 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6.2</generator>
	<language>en</language>
			<item>
		<title>Chrome fallout</title>
		<link>http://unitstep.net/blog/2008/09/04/chrome-fallout/</link>
		<comments>http://unitstep.net/blog/2008/09/04/chrome-fallout/#comments</comments>
		<pubDate>Thu, 04 Sep 2008 23:56:02 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[browsers]]></category>

		<category><![CDATA[chrome]]></category>

		<category><![CDATA[firefox]]></category>

		<category><![CDATA[flash]]></category>

		<category><![CDATA[google]]></category>

		<category><![CDATA[internet explorer]]></category>

		<category><![CDATA[microsoft]]></category>

		<category><![CDATA[opera]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=435</guid>
		<description><![CDATA[Since Chrome&#8217;s official release some two days ago it certainly has gotten a lot of press, both positive and negative.
What&#8217;s good
On the positive side, there are some reports that Chrome&#8217;s market share has already surpassed that of Opera, coming in at close to 2.5% when I last checked.  These results should be taken with [...]]]></description>
			<content:encoded><![CDATA[<p>Since Chrome&#8217;s <a href="http://googleblog.blogspot.com/2008/09/google-chrome-now-live.html">official release</a> some two days ago it certainly has gotten a lot of press, both positive and negative.</p>
<h3>What&#8217;s good</h3>
<p>On the positive side, there are <a href="http://getclicky.com/global-marketshare-statistics">some reports</a> that Chrome&#8217;s market share has already surpassed that of Opera, coming in at close to 2.5% when I last checked.  These results should be taken with a grain of salt, as Clicky&#8217;s web analytics might only be used by websites that tend to be visited by those more technically-inclined and thus more likely to try out something like Chrome.  (Though Chrome&#8217;s visibility on Google&#8217;s main page no doubt has some small part in its fast growth)</p>
<p>For what it&#8217;s worth, Google Analytics on my lowly-trafficked site amounted to over 4% of hits in the past five days.  (Google Analytics has since <a href="http://analytics.blogspot.com/2008/09/chrome-now-showing-as-browser-type.html">started identifying Chrome</a> as a specific browser type, no surprise)</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-fallout-1.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-fallout-1-300x46.jpg" alt="Chrome browser share" title="google-chrome-fallout-1" width="300" height="46" class="size-medium wp-image-437" /></a><br />
Chrome browser share on my site
</p>
<h3>What&#8217;s iffy</h3>
<p>While the V8 JavaScript engine of Chrome was reported to be fast (myself included) Mozilla has fired back with <a href="http://arstechnica.com/journals/linux.ars/2008/09/03/new-firefox-javascript-engine-is-faster-than-chromes-v8">their own results</a> when compared to the upcoming Firefox 3.1, which also features a newer, faster JavaScript engine dubbed <a href="http://ejohn.org/blog/tracemonkey/">TraceMonkey</a>.</p>
<p>Even if this only manages to bring Firefox 3.1 to within striking distance of Chrome for JavaScript performance, it&#8217;ll still easily hand the win over to Firefox 3.1 considering its much larger established base and support for extensions/addons.</p>
<p>Microsoft, meanwhile, still seems to have their <a href="http://arstechnica.com/journals/microsoft.ars/2008/09/04/microsoft-in-response-to-chrome-users-will-still-want-ie8">heads in the sand</a> when it comes to IE.  True, IE7 still have a substantial margin on any other browser but that lead has been steadily sinking.  Though IE8 will likely be a vast improvement over IE7 and seeks to erase all memories of the abomination that was IE6, it looks like Microsoft will have its work cut out with the stiff competition from Firefox and Chrome.</p>
<h3>Problems</h3>
<p>The release was not without controversy, as since this product was from Google, many privacy concerns were voiced.  There were concerns about the &#8220;GoogleUpdate.exe&#8221; process that is installed with Chrome, which apparently allows for <a href="http://tech.slashdot.org/comments.pl?sid=952157&#038;threshold=1&#038;commentsort=1&#038;mode=thread&#038;cid=24859505">higher privileges to install software</a>, which understandably freaked out some users.  Generally, unwanted processes running in the background are just the thing the tinfoil-hat wearers are looking for.</p>
<p>Additionally, some keen-eyed users who perused the EULA discovered that Google had apparently tried to <a href="http://arstechnica.com/news.ars/post/20080903-google-on-chrome-eula-controversy-our-bad-well-change-it.html">claim ownership of all content posted</a> through Chrome.  (Who <em>actually</em> reads a EULA?)  Evidently, it was all a mishap, as Google quickly moved to <a href="http://googleblog.blogspot.com/2008/09/update-to-google-chromes-terms-of.html">correct the errors in the TOS</a>.  Apparently, in the rush to release Chrome, a &#8220;standard&#8221; TOS was used as the basis for the EULA, most likely similar to the ones covering services like Blogger, etc.</p>
<h3>My own experiences</h3>
<p>Personally, I&#8217;m very pleased with the browser.  The &#8220;application shortcut&#8221; feature is very nice as it makes web apps like Gmail integrate very nicely with the desktop.  I can&#8217;t wait to setup my Mom&#8217;s computer with shortcuts to things like Gmail that will undoubtedly make her life easier.</p>
<p>The JavaScript performance <em>is</em> very fast compared to other browsers, but some things like Flash are still buggy at times.  This has caused problems with sites like Google Finance (which uses Flash for the charts) and YouTube, which are ironically Google&#8217;s own services.</p>
<p>I guess the &#8220;Beta&#8221; tag and the lack of a full version number excuse these problems, though it looks as if the list of bugs is already quite extensive.  <a href="http://code.google.com/p/chromium/issues/list">Google&#8217;s bug tracker</a> for Chrome lists over a thousand bugs/feature requests currently, though likely many of them are duplicates.  (Google is, however, following the trend of using the &#8220;Beta&#8221; moniker in an increasingly loose manner)</p>
<hr/>Copyright &copy; 2008 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/09/04/chrome-fallout/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Google Chrome: What it offers</title>
		<link>http://unitstep.net/blog/2008/09/02/google-chrome-what-it-offers/</link>
		<comments>http://unitstep.net/blog/2008/09/02/google-chrome-what-it-offers/#comments</comments>
		<pubDate>Wed, 03 Sep 2008 01:03:15 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
		
		<category><![CDATA[Ajax]]></category>

		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[XHTML]]></category>

		<category><![CDATA[browsers]]></category>

		<category><![CDATA[chrome]]></category>

		<category><![CDATA[comparison]]></category>

		<category><![CDATA[development]]></category>

		<category><![CDATA[firefox]]></category>

		<category><![CDATA[google]]></category>

		<category><![CDATA[internet explorer]]></category>

		<category><![CDATA[opera]]></category>

		<category><![CDATA[reviews]]></category>

		<category><![CDATA[web2.0]]></category>

		<category><![CDATA[gears]]></category>

		<category><![CDATA[ie]]></category>

		<category><![CDATA[mozilla]]></category>

		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=411</guid>
		<description><![CDATA[
After much speculation yesterday, marked by a leaked web comic and finally an acknowledgment by Google, Google Chrome, the much anticipated web browser, is here.
I encourage you to download it and give it a try, as I did as soon as it came out.  Here are some of my initial impressions.
Overview
Google released a fairly [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome.jpg" alt="Google Chrome" /></p>
<p>After much <a href="http://blogoscoped.com/archive/2008-09-01-n47.html">speculation yesterday</a>, marked by a <a href="http://www.google.com/googlebooks/chrome/index.html">leaked web comic</a> and finally an <a href="http://googleblog.blogspot.com/2008/09/fresh-take-on-browser.html">acknowledgment by Google</a>, <a href="http://www.google.com/chrome/intl/en/features.html">Google Chrome</a>, the much anticipated web browser, <a href="http://googleblog.blogspot.com/2008/09/google-chrome-now-live.html">is here</a>.</p>
<p>I encourage you to <a href="http://www.google.com/chrome/index.html">download it</a> and give it a try, as I did as soon as it came out.  Here are some of my initial impressions.</p>
<h3>Overview</h3>
<p>Google released a fairly long <a href="http://www.google.com/googlebooks/chrome/">web comic</a> that delves into quite a bit of detail about Chrome - it&#8217;s not your typical comic!  Touted as being built &#8220;from scratch&#8221;, Chrome uses the WebKit rendering engine, the same one that powers Safari and Konqueror.</p>
<p class="image"><a href="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-2.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-2-300x207.jpg" alt="" title="google-chrome-2" width="300" height="207" class="alignnone size-medium wp-image-420" /></a></p>
<p>The first thing you notice is how minimal the &#8220;Chrome&#8221; or UI of Chrome is.  If you&#8217;re used to a half-dozen toolbars, buttons and widgets all over the place, Chrome will seem like a greenfield to you.  By default, there is only a tab bar and then an address bar containing back, forward, a combined reload-stop button and the address bar.  There are also buttons for bookmarking a site and for page and browser settings.  The bookmarks bar is not displayed unless you specifically change that setting.</p>
<p>Keyboard shortcuts are also present so that you don&#8217;t have to click through context menus.  If you&#8217;re used to the keyboard shortcuts of Firefox and IE7 you&#8217;ll be pleased to know that most of them transfer over without change: Ctrl-T opens a new Tab, Ctrl-W/Ctrl-F4 closes a tab, Alt-D focuses the address bar and Ctrl-J opens Downloaded Files.</p>
<p>The address bar also functions as a search bar, and this combination just makes sense.  It&#8217;s something I&#8217;ve always been doing using <a href="http://lifehacker.com/software/geek-to-live/geek-to-live-fifteen-firefox-quick-searches-129658.php">Firefox Quick Searches</a></p>
<p>By default the home/start page is set to set to show an Opera-style &#8220;<a href="http://www.opera.com/support/tutorials/flash/speeddial/">Speed Dial</a>&#8221; page containing most recently-accessed pages/bookmarks.  You can also configure Chrome to restore the previous tabs/websites on startup, which is my personal preference ever since I started using Firefox.</p>
<h3>Features</h3>
<p>Chrome integrates Google Gears to speed up supporting web applications and is an obvious effort by Google to self-promote. This is substantial since the download link for Chrome is on the main Google search page - no small feat considering only the most popular/important services get that sort of attention and furthermore the link is positioned dead center beneath the search field.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-3.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-3-300x210.jpg" alt="" title="google-chrome-3" width="300" height="210" class="alignnone size-medium wp-image-422" /></a><br />
The address/search bar
</p>
<p>Chrome allows for quasi-<a href="http://en.wikipedia.org/wiki/Site_Specific_Browser">Site-Specific Browsers</a> by use of &#8220;Application Shortcuts&#8221;, which can be set for any website but are meant to be used mainly with web applications.  These allow you to open the target <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> in a browser window that does not have the menu or address bars and essentially serves as a blank canvas upon which the web application&#8217;s own UI can be displayed.  </p>
<p>This is similar to other SSBs such as <a href="https://wiki.mozilla.org/Prism">Mozilla Prism</a> or <a href="http://fluidapp.com/">Fluid</a> for the Mac, as they aim to bridge the gap between desktop and web applications to make their integration more seamless.</p>
<p>However, like <a href="http://blogoscoped.com/archive/2008-09-01-n47.html">Google Blogoscoped points out</a>, using such non-browser interfaces may condition the user to be more lax when entering their credentials and makes phishing attempts more viable since no <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> is displayed.  This is curious since security, &#8220;sandboxing&#8221; and general safe browsing were so high on Chrome&#8217;s feature list - this feature seems to help undo some good user practices of always confirming the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> before entering credentials. </p>
<p>There are also some nice little enhancements as well - the combined address bar/search bar is very much like Firefox 3&#8217;s &#8220;awesome bar&#8221;.  Chrome also allows you to dynamically resize any <code>textarea</code> element, without the site designer having to code this specifically in JavaScript or some other client-side technology.</p>
<h3>Performance</h3>
<p>Each tab/window is a separate process and thus will show up separately in Task Manager; Chrome also offers its own Task Manager but the memory usage reported here differs from that in the Windows Task Manager.  To get the full picture, you have to click on the &#8220;Stats for nerds&#8221; link, which takes you to <code>about:memory</code></p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-4.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-4-300x192.jpg" alt="" title="google-chrome-4" width="300" height="192" class="alignnone size-medium wp-image-424" /></a>
</p>
<p>This page displays the full memory usage details, and also, surprisingly, displays memory usage for any other web browsers also currently running! (I have confirmed that it will display Firefox 2/3, IE7 and Opera 9)</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-5.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-5-300x208.jpg" alt="" title="google-chrome-5" width="300" height="208" class="alignnone size-medium wp-image-425" /></a>
</p>
<p>Much talk has been made of this feature; indeed while it does use more resources, it also prevents a single site from bringing down the entire browser as only that tab/window will be affected.  To test this out, just terminate one of the instances of chrome.exe and you will see that tab&#8217;s screen into a &#8220;sad tab of death&#8221; with an amusing message.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-1.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-1.jpg" alt="" title="google-chrome-1" width="346" height="313" class="alignnone size-full wp-image-415" /></a>
</p>
<h3>JavaScript</h3>
<p>Though JavaScript falls under the category of `Performance` I felt it deserves its own section because of the importance of JavaScript in web applications.  Chrome uses the Google-developed V8 JavaScript engine, which has also been <a href="http://code.google.com/apis/v8/">released as open source</a>.</p>
<p>The <a href="http://code.google.com/apis/v8/design.html">main points</a> of V8 are outlined at the Google Code page for the project, and are quite interesting.  One of the main improvements in performance is the use of a Virtual Machine (VM) for processing JavaScript.</p>
<p>The V8 Virtual Machine is different from say, the JVM (Java Virtual Machine) in that it compiles JavaScript source <em>directly to machine code</em>; there is no intermediate byte-code representation used and hence no interpreter is needed for this.  This seems to indicate that JavaScript performance might be faster on Chrome since there&#8217;s no intermediary. Google provides some <a href="http://code.google.com/apis/v8/benchmarks.html">benchmarks</a> to confirm this.</p>
<p>From some informal/unscientific preliminary testing, the V8 JavaScript engine in Chrome <em>does</em> appear to be quite fast; loading the same Digg topic in Firefox took longer than it did in Chrome. (Roughly 14 secs vs. 8 seconds over a few trials - and Chrome did not have the benefit of AdBlock Plus) I&#8217;d be <em>very</em> interested to see how Chrome stacks up against Firefox 3.1, considering the rumoured <a href="http://arstechnica.com/news.ars/post/20080822-firefox-to-get-massive-javascript-performance-boost.html">performance boosts</a> coming with it.</p>
<p>If Chrome has anything going for it, it&#8217;s definitely the lightning fast JavaScript performance.  Coupled with the crash-proofing this makes it ideal for use in web applications.</p>
<h3>Development</h3>
<p>Chrome comes with a nice DOM inspector reminiscent of Firebug.  Using it is dead simple; you just right click and select &#8220;Inspect Element&#8221; and the inspection window will pop up with the element highlighted.  Here you can see the full DOM tree as well as the computed <acronym class="uttInitialism" title="Cascading Style Sheets">CSS</acronym> styles for the element.  </p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-6.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/09/google-chrome-6-300x231.jpg" alt="" title="google-chrome-6" width="300" height="231" class="alignnone size-medium wp-image-427" /></a>
</p>
<p>There&#8217;s an included JavaScript console for executing code/commands/expressions on-the-fly and while there is a JavaScript debugger included, it seems at this time to be a command-line only tool, far less user-friendly than Firebug.</p>
<h3>Not ready for prime time yet?</h3>
<p>Of course, Chrome is marked as Beta by Google, something we&#8217;ve come to expect since Gmail has been in beta for longer than the company has been publicly traded.  Nonetheless, there are still some features that are sorely missed.</p>
<p>The one thing I absolutely love about Firefox is the vibrant developer community and subsequent widespread availability of quality, useful extensions.  This has produced such gems as the aforementioned <a href="https://addons.mozilla.org/en-US/firefox/addon/1843">Firebug</a> and <a href="http://adblockplus.org/en/">Adblock Plus</a>.  </p>
<p>For now, extensions/addons are not part of Chrome but may be added in a later version.  In the meantime I don&#8217;t think I&#8217;ll be even close to ready to switch, as I&#8217;m very stubborn.  I don&#8217;t use that many extensions but the few that I do are &#8220;must-haves&#8221; and I just can&#8217;t browse without them.  </p>
<p>Lastly, there are always privacy concerns, especially from a company as big an involved as Google.  Though you can turn off the sending of usage statistics, there will always be some with their tinfoil hats on.</p>
<h3>Conclusions</h3>
<p>All things considered, Chrome is a very good entry into the browser market.  While I don&#8217;t think it&#8217;s ready to take on Firefox or IE yet, it does provide competition.  So as long as Chrome continues to support standards (which I think it will, since it uses the WebKit renderer and Google has also been forthcoming with their <a href="http://www.google.com/chrome/intl/en/webmasters.html">support for web developers</a>), I won&#8217;t have a problem with it.  I won&#8217;t be switching over to it anytime soon, but at the very least it&#8217;ll be a useful development tool to verify/test my websites on to make sure they look proper in Safari/Konqueror/Chrome.</p>
<hr/>Copyright &copy; 2008 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/09/02/google-chrome-what-it-offers/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Upgrade jQuery for better Opera support (Or just upgrade Opera)</title>
		<link>http://unitstep.net/blog/2008/06/25/upgrade-jquery-for-better-opera-support-or-just-upgrade-opera/</link>
		<comments>http://unitstep.net/blog/2008/06/25/upgrade-jquery-for-better-opera-support-or-just-upgrade-opera/#comments</comments>
		<pubDate>Thu, 26 Jun 2008 00:45:43 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[browsers]]></category>

		<category><![CDATA[jQuery]]></category>

		<category><![CDATA[opera]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=336</guid>
		<description><![CDATA[I ran into a weird problem while testing one of my sites that used jQuery with Opera 9.26.  (I happened to be using this older version of Opera because I am lazy to upgrade; I&#8217;m still using Firefox 2 despite the successful launch of FF3)
The issue was with an Ajax request I was sending. [...]]]></description>
			<content:encoded><![CDATA[<p>I ran into a weird problem while testing one of my sites that used jQuery with Opera 9.26.  (I happened to be using this older version of Opera because I am lazy to upgrade; I&#8217;m still using Firefox 2 despite the successful launch of FF3)</p>
<p>The issue was with an Ajax request I was sending.  The return value was an array in JSON form.  More specifically, the server was returning something like:</p>
<pre><code>{tag:[{id1:'A',id2:'B'}, {id1:'A',id2:'B'}, {id1:'A',id2:'B'}]}</code></pre>
<p>This was perfectly valid and worked fine in both Firefox and Internet Explorer.  However, in Opera 9.26, I got a JavaScript error indicating that the JSON was not valid.  It was then that I realized I was using an older version of jQuery, v1.2.2.  <a href="http://docs.jquery.com/Downloading_jQuery">Upgrading to the latest</a>, 1.2.6 fixed the problem.  Strangely, I could not find anything on their bug tracker indicating that such a problem (JSON and Opera) had been fixed.</p>
<p>What was even more interesting was that <a href="http://www.opera.com/download/">upgrading to Opera 9.50</a> also solved the problem independently; that is, things worked fine even with the older version of jQuery.  This goes to show the importance of keeping your software up to date and highlights the complicated interactions between different browsers and client-side code in a web application.</p>
<hr/>Copyright &copy; 2008 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/06/25/upgrade-jquery-for-better-opera-support-or-just-upgrade-opera/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Playing with Google Maps and encoded polylines</title>
		<link>http://unitstep.net/blog/2008/05/11/playing-with-google-maps-and-encoded-polylines/</link>
		<comments>http://unitstep.net/blog/2008/05/11/playing-with-google-maps-and-encoded-polylines/#comments</comments>
		<pubDate>Mon, 12 May 2008 01:35:59 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[development]]></category>

		<category><![CDATA[google]]></category>

		<category><![CDATA[maps]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[documentation]]></category>

		<category><![CDATA[google maps]]></category>

		<category><![CDATA[polylines]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=324</guid>
		<description><![CDATA[
I&#8217;ve been playing around with the Google Maps API for a bit and it&#8217;s turned out to be a great way to get started with &#8220;mashups&#8221; and the like.  One of the best uses of the API is the ability to create paths or routes on the map.
This is done by creating GPolyline object [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><img src="http://unitstep.net/wordpress/wp-content/uploads/2008/05/google-maps.gif" alt="" title="google-maps" /></p>
<p>I&#8217;ve been playing around with the <a href="http://code.google.com/apis/maps/documentation/index.html">Google Maps API</a> for a bit and it&#8217;s turned out to be a great way to get started with &#8220;mashups&#8221; and the like.  One of the best uses of the API is the ability to create paths or routes on the map.</p>
<p>This is done by creating <a href="http://code.google.com/apis/maps/documentation/overlays.html#Polylines_Overview"><code>GPolyline</code></a> object and then adding it as an overlay to the map.  Basically, a polyline is just an ordered list of geographical points/coordinates on the map, each of which is a <a href="http://code.google.com/apis/maps/documentation/reference.html#GLatLng"><code>GLatLng</code></a> object.  For serialization/storage of polylines, there is an <a href="http://code.google.com/apis/maps/documentation/polylinealgorithm.html">algorithm you can use</a> to Base64-encode a series of points; the resultant string can later be passed directly into a factory method to regenerate the <code>GPolyline</code>.  By using encoded polylines, you also get access to a few more interesting and useful options related to rendering and performance issues.</p>
<h3>Encoded Polylines</h3>
<p>Despite the <a href="http://code.google.com/apis/maps/documentation/polylinealgorithm.html">algorithm for encoding polylines</a> being readily available on the Google Maps API documentation site, there is no built-in functionality within the API for generating the encoded polyline string from an existing <code>GPolyline</code> object.  This might be a bit strange, but it&#8217;s probably because the encoding process requires some extra values that aren&#8217;t available in the typical polyline.</p>
<p>As specified on the algorithm page, you also need to specify a list of encoded &#8220;levels&#8221; in addition to the points themselves.  These levels tell the the Google Maps renderer when certain points can be omitted from the polyline depending on the zoom level.  For example, with a polyline with <em>n</em> points, you&#8217;ll <strong>always</strong> want to show the first and last point, no matter what the zoom level.  However, intermediate points can potentially be omitted at low zoom levels and only shown when the map has been sufficiently zoomed in to warrant the detail.  This sort of optimization cannot be done with the typical <code>GPolyline</code> constructor that just takes an array of points. (<code>GLatLng</code> objects)</p>
<h3>Making things easy</h3>
<p>If you&#8217;ve looked at the <a href="http://code.google.com/apis/maps/documentation/polylinealgorithm.html">polyline encoding algorithm</a>, you&#8217;ll probably notice that it&#8217;s a bit tricky unless you&#8217;ve taken course in CS or done a lot of this stuff before. (At least it was tricky for me)  Google has an <a href="http://code.google.com/apis/maps/documentation/polylineutility.html">interactive utility</a> for generating the encoded polyline format for you.  The results can then be stored and later fed into a call to the factory method <a href="http://code.google.com/apis/maps/documentation/reference.html#GPolyline"><code>GPolyline.fromEncoded()</code></a> to regenerate the polyline.</p>
<p>However if you want to generate the encoded polyline format on-the-fly as part of your application, the interactive utility is not really an option.  Instead of coding the algorithm from the ground-up, there&#8217;s a much better way of doing things, thanks to the <a href="http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/">PolylineEncoder class</a> and other utilities provided by <a href="http://facstaff.unca.edu/mcmcclur/">Mark McClure</a>.</p>
<p>The <a href="http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/PolylineEncoderClass.html">PolylineEncoder class</a> is written in JavaScript and is very straightforward in its usage.  (It has been ported to several other languages as listed on <a href="http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/">his site</a>, in case you need to use it in different contexts)</p>
<p>Using this class allows you to quickly and easily convert a <code>GPolyline</code> into a compact encoded format useful for serialization or storage.  You can also use the class to convert arrays of points into encoded polylines, thus gaining the benefit of optimized rendering at different zoom levels.  McClure goes into an in-depth, but easy to understand <a href="http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/algorithm.html">explanation of the encoding algorithm used</a> complete with animations that show exactly how the polyline approximations work.</p>
<p>I highly recommend the usage of his polyline encoder as it saves you the headache of implementing it yourself.  It&#8217;s well-written, thoroughly documented and is free for usage. (It isn&#8217;t licensed under open-source terms but has instead been placed in the public domain - which is perhaps even more &#8220;free&#8221;) McClure also has a few other <a href="http://facstaff.unca.edu/mcmcclur/GoogleMaps/">interesing Google Maps projects</a> that you may want to check out.</p>
<h3>Some documentation warnings</h3>
<p>The Google Maps API documentation is fairly thorough, but it&#8217;s out of date in some places, as <a href="http://groups.google.com/group/Google-Maps-API/browse_thread/thread/e0861bacc7531b08/b5e504771ebb12c4">some people have found</a>.  Indeed, in this case, it appears that the <code>GPolyline.fromEncoded()</code> is documented somewhat wrongly in the API reference, though curiously, is used properly in their <a href="http://code.google.com/apis/maps/documentation/overlays.html#Polylines_Overview">examples page</a>.  </p>
<p>Specifically, you <strong>should not</strong> use:</p>
<pre><code>GPolyline.fromEncoded(color?,  weight?,  opacity?,  latlngs,  zoomFactor,  levels,  numLevels)</code></pre>
<p>if you want to generate a polyline from the encoded format.  Instead, you should use something like:</p>
<pre><code>GPolyline.fromEncoded({
    color: "#FF0000",
    weight: 10,
    points: "yzocFzynhVq}@n}@o}@nzD",
    levels: "BBB",
    zoomFactor: 32,
    numLevels: 4
});</code></pre>
<p>This is because the API has been updated to accept an object of options instead of separate parameters.  This, in my opinion, is better for readability and takes advantage of JavaScript&#8217;s ability to define inline anonymous object literals.  </p>
<p>As a side note, the example actually calls something like <code>new GPolyline.fromEncoded</code>, but I&#8217;ve found that you don&#8217;t need the <code>new</code> keyword, and in fact, it&#8217;s a bit confusing that the example has it and that it would work - after all, you are calling a factory method that returns a type of <code>GPolyline</code>, and not directly instantiating an object. (At least as far as <a href="/blog/2008/01/24/javascript-and-inheritance/">JavaScript uses the <code>new</code> keyword</a>)</p>
<hr/>Copyright &copy; 2008 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/05/11/playing-with-google-maps-and-encoded-polylines/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Password salting and the modified Challenge-Response system</title>
		<link>http://unitstep.net/blog/2008/04/28/password-salting-and-the-modified-challenge-response-system/</link>
		<comments>http://unitstep.net/blog/2008/04/28/password-salting-and-the-modified-challenge-response-system/#comments</comments>
		<pubDate>Tue, 29 Apr 2008 01:12:42 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
		
		<category><![CDATA[Ajax]]></category>

		<category><![CDATA[CHAP]]></category>

		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[PHP]]></category>

		<category><![CDATA[authentication]]></category>

		<category><![CDATA[chap-php]]></category>

		<category><![CDATA[login]]></category>

		<category><![CDATA[passwords]]></category>

		<category><![CDATA[security]]></category>

		<category><![CDATA[challenge-response]]></category>

		<category><![CDATA[salting]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=312</guid>
		<description><![CDATA[Since I released my demo/example modified Challenge-Response Ajax PHP Login System about a month ago (which was based on ideas from Paul Johnston), I&#8217;ve been receiving some questions about why salting was not incorporated into the system.  In particular, there was a discussion at a Dutch-language forums, which I somewhat understood after Google translation. [...]]]></description>
			<content:encoded><![CDATA[<p>Since I released my demo/example <a href="/blog/2008/03/29/a-challenge-response-ajax-php-login-system/">modified Challenge-Response Ajax <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> Login System</a> about a month ago (which was based on ideas from <a href="http://pajhome.org.uk/crypt/md5/auth.html">Paul Johnston</a>), I&#8217;ve been receiving some questions about why <a href="http://en.wikipedia.org/wiki/Salt_(cryptography)">salting</a> was not incorporated into the system.  In particular, there was a <a href="http://gathering.tweakers.net/forum/list_messages/1284731///salt">discussion</a> at a Dutch-language forums, which I somewhat understood after <a href="http://www.google.com/translate?u=http%3A%2F%2Fgathering.tweakers.net%2Fforum%2Flist_messages%2F1284731%2F%2F%2Fsalt&#038;langpair=nl%7Cen&#038;hl=en&#038;ie=UTF8">Google translation</a>. </p>
<p>Here, I&#8217;ll try to address some of these concerns and answer some questions.</p>
<h3>Salt of the earth</h3>
<p>To understand why salting is used, we must first understand exactly what it is.  Just like regular salt, in cryptography, salting is used to alter the &#8220;taste&#8221; or output of some process. </p>
<p>In the case of password storage, most people would realize that you should <em>never</em> store lists of users&#8217; passwords in plaintext, because if that data is ever compromised, attackers will gain access not only the compromised accounts but could potentially use the passwords to gain access to user accounts on other services/sites.  This is because people often reuse the same passwords across multiple account/services.</p>
<p>The easiest way to avoid this is to store the <em>hash</em> of the password.  A hash is a one-way function, that is, once you compute the hash of a value, you cannot obtain the original from just the hashed value.  Some typical hash functions are MD5 or the more secure family of SHA hash functions.</p>
<p>However, this still doesn&#8217;t fully conceal passwords.  If an attacker were to obtain the list of hashed passwords, they could try a dictionary-based attack to discover the original inputs.  This involves hashing common words to see if they hash to the correct value.  Since people often use common words or combinations of such, a dictionary-based attack has the advantage of having far fewer combinations that the attacker needs to try compared to a true brute-force attack.</p>
<h3>Adding variability</h3>
<p>This problem can be mitigated by salting, which basically amounts to combining the password with additional input before passing it into the hash function.  This alters the end output from the hash function so that a dictionary-based attack cannot be used, <strong>provided the salt is kept a secret</strong>.  A comparison example:</p>
<pre><code>Without salting:
hash(A) -&gt; B;

With salting:
hash (A + S) -&gt; C;</code></pre>
<p>In the first example, salting was not used before hashing.  Assuming the value &#8216;A&#8217; is a common word or phrase, an attacker can use a dictionary-attack to determine what the value of &#8216;A&#8217; was. (I.E. what value hashes to the value of &#8216;C&#8217;)</p>
<p>With salting, things become more difficult.  If the attacker does not know the value of the salt (S), they cannot use a dictionary-based attack because the actual input will not be a common word or phrase.  Instead, they must try all values in the dictionary <em>with</em> all possible values of the salt.  In fact, every bit of the added salt value doubles the number of computations in a dictionary-based attack.  The important point to retain here is the <strong>salt value must be kept a secret</strong> in order to obtain this benefit.</p>
<p>One other benefit of salting is to ensure that two accounts with the same password don&#8217;t produce the same hash.  This can be accomplished by making different accounts have different salts.  The obvious benefit of this is to decrease the information leakage from the hashes, as otherwise, equivalent hashes would infer equivalent passwords.</p>
<h3>Salting and the modified Challenge-Response System</h3>
<p>With the <a href="/blog/2008/03/29/a-challenge-response-ajax-php-login-system/">modified challenge-response system</a>, it isn&#8217;t clear to me how salting could be used to improve it.  Here&#8217;s a quick re-cap of how it works:</p>
<blockquote><p>
Signup:</p>
<p>1. Server sends random1<br />
2. Client sends hex_sha1(hex_hmac_sha1(password, random1))</p>
<p>Login:</p>
<p>1. Server sends random1 and random2<br />
2. Client sends hex_hmac_sha1(password, random1) and hex_sha1(hex_hmac_sha1(password, random2))
</p></blockquote>
<p>To login, the user must present two values: One to verify that they know the password, and the second value, which is used to set the response that must be computed for the <em>next login</em>.</p>
<p>Because the client must compute the next response value, it&#8217;s a bit tricky to implement salting in a way that&#8217;s beneficial. </p>
<p>One possible method would be to further hash the second value (<code>hex_sha1(hex_hmac_sha1(password, random1))</code>) with a <strong>server secret</strong> before storing it in the database.  This would complicate things should the database be compromised but not the server secret, since a dictionary attack would become much harder with the extra variability of a server secret.  In this case, the work flow would look something like this:</p>
<h4>Signup</h4>
<ol>
<li>Server sends random1</li>
<li>Client sends hex_sha1(hex_hmac_sha1(password, random1)) [<strong>Let's call this value `hashed_challenge_response` for brevity</strong>]</li>
<li>Server stores hex_hmac_sha1(server_secret, hashed_challenge_response)</li>
</ol>
<h4>Login:</h4>
<ol>
<li>Server sends random1 and random2</li>
<li>Client sends hex_hmac_sha1(password, random1) and hex_sha1(hex_hmac_sha1(password, random2))</li>
<li>Server computes hex_sha1(hex_hmac_sha1(password, random1)) [<strong>Call this `hashed_challenge_response_received`</strong>]</li>
<li>Server checks if hex_hmac_sha1(server_secret, hashed_challenge_response_received) equals the value previously stored.  If so, authentication was successful and a new challenge-response is stored based on the second value received.</li>
</ol>
<p>Note that this method <strong>would not improve the login security anymore</strong>, since an attacker who captured the intermediate traffic of a successful login could still conduct an offline dictionary attack, which this challenge-response system is unfortunately susceptible to.</p>
<p>However, the modified system does benefit from the use of the `random1` and `random2` challenge strings, which are stored alongside the response values.  Since these are random and different for each user (and for each subsequent login), accounts with the same password will not have the same hash-response.  This effectively gives the second lesser benefit of salting.</p>
<p>The modified challenge-response system also suffers from the inability of the server to enforce strong passwords.  Because the initial value sent during registration is a hashed value of the password and a random value, the server cannot be aware of any properties of the password such as its length or composition.  The only aspect that could be enforced server-side would be to make sure the password was not blank!  My suggestion is to (attempt to) enforce password complexity using JavaScript on the client side.  Such rules can obviously be circumvented but are better than nothing.</p>
<h3>Conclusion</h3>
<p>Hopefully I&#8217;ve shed some light on the topic of salting in relation to the modified challenge-response Ajax <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> login system.  I&#8217;m no security expert, so you should not take my advise as scripture.  Please don&#8217;t hesitate to give me your comments or feedback!</p>
<hr/>Copyright &copy; 2008 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/04/28/password-salting-and-the-modified-challenge-response-system/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A Challenge-Response Ajax PHP Login System</title>
		<link>http://unitstep.net/blog/2008/03/29/a-challenge-response-ajax-php-login-system/</link>
		<comments>http://unitstep.net/blog/2008/03/29/a-challenge-response-ajax-php-login-system/#comments</comments>
		<pubDate>Sun, 30 Mar 2008 01:53:11 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
		
		<category><![CDATA[Ajax]]></category>

		<category><![CDATA[CHAP]]></category>

		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[PHP]]></category>

		<category><![CDATA[authentication]]></category>

		<category><![CDATA[chap-php]]></category>

		<category><![CDATA[login]]></category>

		<category><![CDATA[passwords]]></category>

		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://unitstep.net/blog/2008/03/29/a-challenge-response-ajax-php-login-system/</guid>
		<description><![CDATA[A while ago, (okay, a long while ago) I wrote about a way to improve the security of login/authentication with web applications.  The process involved using challenge-response during authentication to prevent passwords from being transmitted in plaintext.  The idea was not mine, but instead the work of a smart fellow named Paul Johnston. [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago, (okay, a <em>long</em> while ago) I wrote about <a href="/blog/2006/09/19/using-a-chap-login-system-to-improve-security/">a way to improve the security</a> of login/authentication with web applications.  The process involved using challenge-response during authentication to prevent passwords from being transmitted in plaintext.  The <a href="http://pajhome.org.uk/crypt/md5/auth.html">idea was not mine</a>, but instead the work of a smart fellow named <a href="http://pajhome.org.uk/">Paul Johnston</a>.   At the time, I &#8220;hoped to present an actual implementation&#8221; sometime in the future, but never got around to it.  I finally had some time and decided to put together a working example using <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> and JavaScript. </p>
<h3>Download the source</h3>
<p>Please feel free to download and try out the first public release of the CHAP-PHP login system.  The zip file has the full source and provides an example how to implement the system both on the client and server side.</p>
<div class="download">
<a class="icon" href='http://unitstep.net/wordpress/wp-content/uploads/2008/03/chap-php-051.zip' title='CHAP-PHP-0.5.1'>Download CHAP-PHP-0.5.1</a>
</div>
<p>The same demo available in the zip file is also <a href="/projects/CHAP-PHP/src/demo/index.php">available here</a>.</p>
<h3>Improving authentication security with Challenge-Response</h3>
<p>Challenge-Response is the basis for many authentication systems.  In such a situation, a server may have to authenticate a user by verifying their credentials, usually in the form of a password.  However, transmitting plaintext passwords over connections that are not secure can lead to compromises.  In such a situation, <dfn>challenge-response</dfn> may be used.  This usually involves the server sending a <strong>random challenge</strong> string to the client, which must then produce an appropriate <strong>response</strong> that can only be computed using the challenge and the password.  This response is then sent to the server, which can then verify if the right password was used to generate it.  The response is usually computed by hashing a value that depends on the challenge and the password, thus it is not possible to obtain the password from the response, which might have been sniffed on an insecure connection. </p>
<p>However, such a traditional challenge-response has the downside that the plaintext password (or a password-equivalent) must be known to the server at some point.  Paul Johnston came up with <a href="http://pajhome.org.uk/crypt/md5/auth.html">an idea for an alternative system</a> a while ago that overcomes these shortcomings.  (Though it is not free from weaknesses itself)  It is this &#8220;Alternative System&#8221; that the above release is based upon.  Here is a quick explanation of the system, adapted from Johnston&#8217;s site:</p>
<blockquote cite="http://pajhome.org.uk/crypt/md5/auth.html"><p>
Signup:</p>
<p>   1. Server sends random1<br />
   2. Client sends hex_sha1(hex_hmac_sha1(password, random1))</p>
<p>Login:</p>
<p>   1. Server sends random1 and random2<br />
   2. Client sends hex_hmac_sha1(password, random1) and hex_sha1(hex_hmac_sha1(password, random2))
</p></blockquote>
<p>During registration, the value sent by the client is stored.  During login, the user must present a value <em>that when hashed</em> produces the value provided at registration.  Because of the non-reversibility property of hashes, knowing the value passed during registration does not allow an attacker to login.  The only way to produce the valid response is to know the actual plaintext password, which is never transmitted or known by the server.  In this system, challenges are linked to a user and must be stored, since it must be known what challenge was used to produce the response.</p>
<p>The second random challenge (random2) and the second value sent by the client during login are used to prevent replay attacks.  Upon successful login, the second value provided by the client becomes the next response, equivalent to the value first provided during registration.  Thus, for the next login, the value that is sent must hash to equal this value.  This also means that the challenges are updated/changed each time a login is successful.  This has the unfortunate downside of revealing when a user has logged in, since the challenge presented at login will be different.  (Challenges must be publicly available)</p>
<p>For a more thorough explanation, I suggest that you <a href="http://pajhome.org.uk/crypt/md5/auth.html">read Johnston&#8217;s article on the subject</a>.</p>
<h3>Getting it to work</h3>
<p>Understanding the process above leads to the conclusion that user-login is now a two-stage process.  Since the challenges are tied to a user, the username must first be known to the server in order to retrieve the challenge for that user.  The client can then use the challenge to produce the response to send to the server for authentication.</p>
<p>Having a two-stage login form would be very unfriendly to users.  Thus, the main challenge is to make it <em>appear</em> as if nothing out of the ordinary is happening.  This is where Ajax comes into play.  When the form is submitted, the event is prevented from occurring normally.  Instead, the username is first retrieved from the form and sent to the server via an Ajax call in order to retrieve the associated challenge.  Once the challenge is received, the appropriate responses are computed, inserted into the form and then the form is submitted.</p>
<p>The current system also works in the case that JavaScript is not enabled/available on the client side.  In this case, challenge-response will not be available, since JavaScript is used to compute the responses.  The server-side <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> scripts infer that JavaScript <em>was not</em> enabled on the client-side if proper challenge-responses are not received, and thus treat the password as plaintext.  In this case, passwords are transmitted in plaintext.  With this code, you have the choice of allowing this &#8220;insecure&#8221; login to proceed or not.</p>
<p>Note that the CHAP-PHP is more of a module than a full-fledged system, since it&#8217;s not intended to be used on its own but instead as part of some application.  It might be a bit confusing if you&#8217;re a non-developer, but I&#8217;ve tried to make it as straightforward and simple as possible so that it will be easy to integrate with existing code bases/frameworks/sites. </p>
<p>Please don&#8217;t hesitate to <a href="/contact">contact me</a> with your questions, comments or suggestions.</p>
<h3>Disclaimer and warning</h3>
<p>You should not use this as the basis for authentication for sensitive data/websites.  I am not a security expert.  At this point, this is more of a proof-of-concept then something concrete.  It is intended to be the starting point for perhaps something more secure and to show that there are alternatives for more secure authentication when SSL is not available.</p>
<h4>Revision History</h4>
<ul class="note less">
<li>0.5 - First Public Release - 2008-03-29</li>
<li>0.5.1 - Fixed file-based storage to be more robust - 2008-03-30</li>
</ul>
<hr/>Copyright &copy; 2008 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/03/29/a-challenge-response-ajax-php-login-system/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Eclipse: The best and only IDE you&#8217;ll ever need*</title>
		<link>http://unitstep.net/blog/2008/02/10/eclipse-the-best-and-only-ide-youll-ever-need/</link>
		<comments>http://unitstep.net/blog/2008/02/10/eclipse-the-best-and-only-ide-youll-ever-need/#comments</comments>
		<pubDate>Mon, 11 Feb 2008 00:39:16 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[PHP]]></category>

		<category><![CDATA[development]]></category>

		<category><![CDATA[eclipse]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://unitstep.net/blog/2008/02/10/eclipse-the-best-and-only-ide-youll-ever-need/</guid>
		<description><![CDATA[
* Sensationalist headline inspired by previous posts
Eclipse is my IDE of choice, as you&#8217;l probably have noticed from some of my previous articles.  I had been wanting to write an article about why I use it (and why I switched to it), but kept putting it off.  Recently, Matt Mullenweg wrote about his [...]]]></description>
			<content:encoded><![CDATA[<p class="img align-right"><img src='http://unitstep.net/wordpress/wp-content/uploads/2008/02/eclipse-ide.thumbnail.jpg' alt='Copyright The Eclipse Foundation' /></p>
<p class="note less">* Sensationalist headline inspired by <a href="/blog/2007/10/16/sirreals-g15-plugin-the-best-and-only-logitech-g15-sdk-applet-youll-ever-need/">previous posts</a></p>
<p>Eclipse is my IDE of choice, as you&#8217;l probably have noticed from some of my <a href="/blog/2008/01/19/using-assemblas-trac-with-eclipse-mylyn-xml-rpc-access/">previous articles</a>.  I had been wanting to write an article about why I use it (and why I switched to it), but kept putting it off.  Recently, Matt Mullenweg <a href="http://ma.tt/2008/02/wither-dreamweaver/">wrote about his problems with Dreamweaver</a>, and this perhaps prompted me to organize my notes on why I&#8217;ve chosen to use Eclipse.  Don&#8217;t get me wrong - I&#8217;m not advocating that you immediately switch and throw out your current editing tool (the headline above, as noted, is purely for sensationalism) - but rather I&#8217;m just urging you to consider Eclipse for your next project.</p>
<h3>Changing Gears</h3>
<p>Like many, before switching to Eclipse I had been using a pure text editor, Ultraedit, for most of my web-development activities.  Ultraedit seemed fine for <a href="/blog/2007/06/10/ultraedit-php-5-and-the-function-list/">most things</a>, offering basic features like code highlight and autocompletion.  However, it lacked a certain finesse when it came to dealing with larger projects.  For example, if you&#8217;d defined a class, its members wouldn&#8217;t be available for autocompletion.  Something else was needed.  I finally decided to take the plunge, and switch over to Eclipse for all my development towards the end of the summer last year.</p>
<p>Some might wonder why I was even using a text-editor in the first place for development.  For those coming from a traditional programming/development background, the idea of not using an IDE (Integrated Development Environment) is silly.  This is because a lot of programming languages are compiled, and in this case, it just makes sense to use an IDE since it&#8217;s easier to write code, compile and debug using one tool instead of multiple ones. </p>
<p>However, for scripting languages, especially those meant to run on a web server, one can &#8220;get away&#8221; with not using an IDE quite easily.  This is because the scripts are not run standalone but are almost always executed in the context of a web server; thus you&#8217;re usually editing code that you then run on a development web server, without the need for a special tool like a compiler.  Additionally, it&#8217;s easy to view the output using any web browser.  These reasons are what allowed me to persist in using a text-editor for so long.</p>
<h3>No turning back</h3>
<p>However, once I started using Eclipse, I was hooked.  I downloaded Eclipse PDT (<acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> Development Tools), which is basically a version of Eclipse bundled with the tools/plugins necessary for setting up a <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> development environment.  Besides offering everything Ultraedit did, it also offered nice features like easy &#8216;Todo&#8217; lists, (just type &#8216;todo&#8217; anywhere in a comment and it&#8217;s automatically indexed by Eclipse into a list), code completion for built-in <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> functions and your own as well as a multitude of other advanced features that IDEs have.  Oh, and it&#8217;s also FOSS. (Free and Open Source Software)</p>
<p>However, perhaps the best part about Eclipse is its robust and well-supported plugin system.  This allows Eclipse to pretty much assume any feature that someone is willing to write a plugin for.  This is what really sold me on Eclipse, because this almost makes its abilities endless.  Some of the plugins I use are <a href="http://subclipse.tigris.org/">Subclipse</a> for SVN integration, <a href="http://www.eclipse.org/mylyn/">Mylyn for Trac integration</a> and <a href="http://labs.adobe.com/technologies/jseclipse/">JSEclipse</a> for JavaScript editing.  This is part of the reason why Eclipse is the <a href="http://en.wikipedia.org/wiki/List_of_Eclipse-based_software">basis for many other IDEs</a> out there.</p>
<p>Some other nice features are the ability to link the IDE in with the <a href="http://www.zend.com/en/community/pdt#debugger">Zend Debugger</a>, thus allowing for proper debugging sessions with <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym>.</p>
<h3>Spoiled</h3>
<p>However, I&#8217;ve been pampered somewhat and have found a few things to complain about, at least when it comes to Eclipse PDT.  I use Eclipse JDT (Java) a work and its advanced <a href="http://en.wikipedia.org/wiki/Refactoring">refactoring abilities</a> are a feature I find myself wanting in the PDT version.  Have you ever found yourself wanting to rename a variable to something more descriptive but putting it off because you&#8217;re afraid you&#8217;ll mess something up by forgetting to change the name somewhere?</p>
<p>With some IDEs, you&#8217;re left having to just do a search-and-replace in order to accomplish what should be a trivial name refactor.  Even if your editor supports regex searches, things can still be tricky - what if you&#8217;ve used the same name, but in a different context, and thus shouldn&#8217;t change the variable there?  The point is, the process still has to be human-supervised and is tedious.  With Eclipse JDT&#8217;s advanced refactoring, you can rename the variable once - and the IDE is smart enough to know where else to change it to keep the code consistent - <strong>very</strong> neat, and I was amazed when I first used it.  Other refactoring abilities include extracting methods out of blocks of code in order to clean up lengthy methods.  All of this makes your life 10 times easier and allows you focus on real programming rather than annoying tasks.</p>
<p>However, Eclipse PDT doesn&#8217;t support this for <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> code, yet.  I hear that it may be supported in a <a href="http://wiki.eclipse.org/PDT/1.5_Features_Proposal">later release</a>, so I have my fingers crossed.  Perhaps accomplishing these refactoring tasks is easier in Java because of its compiled nature or because the JDT project has received more attention.  It&#8217;s definitely possible in <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym>, as some IDEs, such as the <a href="http://www.zend.com/en/products/studio/">Zend Studio</a> (which is based on Eclipse) support this ability.  Zend Studio, however, is a commercial solution and I haven&#8217;t tried it out yet.</p>
<h3>Nothing&#8217;s perfect</h3>
<p>Eclipse does have its downsides as compared to a traditional text editor.  First of all, it&#8217;s a memory hog - though most IDEs are.  I have regularly seen Eclipse eat up 300-400 MB of RAM if I&#8217;ve been using it for a long time.  However, it should be noted that I have not had it crash once, so it&#8217;s been rock-solid as far as stability goes.  Nonetheless, I recommend you to have at least 2 GB of memory if you really want to use it properly, since you&#8217;re likely to have other programs open.  This is especially important if you&#8217;re running Windows Vista.  RAM is quiet cheap nowadays, and you can easily pick up 2 GB for $50 or less and upgrading is a painless process, so there&#8217;s no reason not to.</p>
<h3>Finishing up</h3>
<p>Eclipse has changed my life.  Okay, so perhaps I&#8217;m exaggerating a bit.  But, I can say that development, at least for me, would be much harder without Eclipse.  If you&#8217;re still using a text editor for development, I urge you to give Eclipse a try - just for 30 days, and see how you like it.  I don&#8217;t guarantee results as good as mine, but you may be pleasantly surprised.</p>
<hr/>Copyright &copy; 2008 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/02/10/eclipse-the-best-and-only-ide-youll-ever-need/feed/</wfw:commentRss>
		</item>
		<item>
		<title>JavaScript and inheritance</title>
		<link>http://unitstep.net/blog/2008/01/24/javascript-and-inheritance/</link>
		<comments>http://unitstep.net/blog/2008/01/24/javascript-and-inheritance/#comments</comments>
		<pubDate>Fri, 25 Jan 2008 03:22:35 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[guides]]></category>

		<category><![CDATA[inheritance]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[prototype]]></category>

		<guid isPermaLink="false">http://unitstep.net/blog/2008/01/24/javascript-and-inheritance/</guid>
		<description><![CDATA[JavaScript has a complicated history.  The name itself seems to indicate a relationship to Java, when in fact, the two languages share little in common except for a common syntax relationship by way of C.  Add to this the myriad of browser incompatibilities and numerous examples of bad usage, and you have what [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript has a complicated history.  The <a href="http://en.wikipedia.org/wiki/Javascript#History_and_naming">name itself</a> seems to indicate a relationship to Java, when in fact, the two languages share little in common except for a common syntax relationship by way of C.  Add to this the myriad of browser incompatibilities and numerous examples of bad usage, and you have what is perhaps the world&#8217;s least understood popular programming language.  (I had to add the &#8216;popular&#8217; qualifier, since I am sure there are some esoteric languages out there that only a handful of people know)</p>
<p>This is why inheritance in JavaScript is probably one of the least understood concepts.  While languages like Java have well-defined constructs for inheritance, the topic is of less importance with JavaScript.  In many situations, you&#8217;ll never have to deal with these aspects when programming in JavaScript, simply because it isn&#8217;t required for a lot of client side scripts.  However, for larger-scale web applications, applying object-oriented principles to your code may make it easier to design, improve and maintain.</p>
<p>There have been <a href="http://javascript.crockford.com/inheritance.html">many</a> <a href="http://javascript.crockford.com/prototypal.html">articles</a> <a href="http://20bits.com/2007/03/08/the-philosophy-of-javascript/">written</a> about inheritance in JavaScript and how it can and should be done.  You really don&#8217;t need to read mine to gain an understanding.  Rather, I&#8217;m just going to write about what I&#8217;ve learned, the process I went through and the experience I&#8217;ve gained along the way. </p>
<h3>It&#8217;s all new(s) to me</h3>
<p>If you come from a Java background, you&#8217;ll be no stranger to the <code>new</code> keyword.  Using it allows you to instantiate a new instance of an object from its class by calling its constructor.  The keyword also makes a lot of sense, since you&#8217;re creating a &#8216;new&#8217; object.</p>
<p>JavaScript also has a <code>new</code> keyword, but it doesn&#8217;t do quite the same thing as its Java counterpart, though at first the effects might seem similar.  This is one of the main reasons why JavaScript inheritance tends to be poorly understood.  </p>
<p>Consider the following example.</p>
<pre><code>function Foo(name)
{
  this.name = name;
}

var fooObject = new Foo('I am foo');</code></pre>
<p>If you&#8217;re familiar with Java or JavaScript, this example is fairly straightforward.  In the prototype-based JavaScript, <a href="http://en.wikipedia.org/wiki/Javascript#Prototype-based_features">functions can serve as object constructors</a> in somewhat the same manner as a constructor in Java.  However, <code>Foo</code> in the above example is not a class, since classes do not exist in JavaScript.  So, if <code>Foo</code> is not a class, what exactly happens when the statement <code>var fooObject = new Foo('I am foo')</code> is executed?</p>
<h3>Taking a step back</h3>
<p>Before we dive into the details, I&#8217;ll explain the concepts of a prototype-based language as it applies to JavaScript.  I mentioned above that JavaScript does not use classes like Java does.  This basically means that new objects are not created from instantiation of classes, but rather inherit from existing objects.  Thus, there is no &#8220;class hierarchy&#8221; but rather just an object hierarchy.  </p>
<p>In JavaScript, all objects are descended from the built-in <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Object"><code>Object</code></a> type.  This is similar to how all Java classes implicitly have the Object class as a superclass.  In JavaScript, instead of extending classes, you can inherit by manipulating the <code>prototype</code> property on a type; that is, the <code>prototype</code> property on the function you are using to create an object.  Let&#8217;s see some code to straighten things out.</p>
<pre><code>function Foo(name)
{
  this.name = name;
}
<strong>Foo.prototype.getName = function()
{
  alert(this.name);
}</strong>

var fooObject = new Foo('I am foo');
<strong>fooObject.getName(); // Will alert with 'I am foo'</strong></code></pre>
<p>This example is identical to the first one, except for the lines that are emphasized.  Here, I&#8217;ve set the <code>getName</code> property on the <code>prototype</code> property of <code>Foo</code> equal to a reference to a Function object.  This is effectively the same as defining a method for a class, since any object created from that type can call the method <code>getName()</code> on itself to return the proper value.  But what exactly is happening, and what&#8217;s the deal with the <code>prototype</code> property?</p>
<h3>More new(s)</h3>
<p>In JavaScript, the <code>new</code> keyword actually accomplishes a few things.  When you execute an expression such as <code>var fooObject = new Foo('I am foo')</code>, here&#8217;s exactly what happens.</p>
<ol>
<li>
First, a new generic object is created.  This object is the same as if you created the object using the statement <code>new Object()</code>, using JavaScript&#8217;s <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Object">built in Object type</a>.
</li>
<li>
The constructor function, that is, the function <code>Foo()</code>, is then called with the <code>this</code> keyword set to reference the newly-created object.  The parameters supplied are also passed to the constructor function, in this case, the string &#8220;I am foo&#8221;.  If you&#8217;re familiar with <a href="/blog/2007/12/18/using-the-call-and-apply-methods-to-change-the-context-of-a-function-in-javascript/">context</a>, this is equivalent to:</p>
<pre><code>var fooObject = new Object();
Foo.call(fooObject, 'I am foo');</code></pre>
<p>Thus, the code in <code>Foo()</code> sets a property called <code>name</code> equal to the supplied string.  Up to this point, things are the same as if you had created a new object and then manually set the <code>name</code> property yourself.  The next step is where things change.
</li>
<li>
The last step is where inheritance takes effect.  The constructor function, in addition to executing the specified code above, also sets an internal property called <code>__proto__</code> equal to the value of <code>Foo.prototype</code>.  This is how the new object inherits from the old one.</p>
<p>When you call a property on <code>fooObject</code> now, JavaScript will first check to see if the object has a local value for it.  In this case, the only local property is <code>name</code>. (Besides the internal and implicitly set <code>__proto__</code> property.  However, if it does not exist locally, it will check to see if the property exists under the object referenced by the <code>__proto__</code> property.  In this case, the <code>getName()</code> method exists under here.
</li>
</ol>
<p>Where things get confusing is because of how the <code>new</code> keyword is used.  Perhaps the designers of JavaScript wanted to use a keyword familiar to Java programmers so as to ease the transition to a new language that sounded so similar.  While it accomplishes a similar goal and for the most part you can consider the action to be almost the same, the use of the <code>new</code> keyword conceals the true meaning of prototype-based inheritance in JavaScript.  This ends up causing more confusion when you start digging into code.</p>
<h3>We&#8217;re all the same</h3>
<p>Suppose you created multiple objects from the <code>Foo()</code> constructor, called <code>fooObject1</code>, <code>fooObject2</code> and <code>fooObject3</code>,   In one fell swoop, you could add a new method to all of these objects without having to recreate them.  This is because of the <code>prototype</code> property.  Because each object contains a reference to <code>Foo.prototype</code>, adding a new method here will allow all objects access to it.  For example:</p>
<pre><code>Foo.prototype.yellName = function()
{
  alert(this.name.toUpperCase());
}
var fooObject3 = new Foo('I am Foo 3!');
fooObject3.yellName(); // alerts 'I AM FOO 3!'</code></pre>
<p>This adds another method to all <code>Foo</code>-constructed objects allowing them to &#8220;yell&#8221; their names.</p>
<h3>Extending Types</h3>
<p>I mentioned inheritance above but with just one type definition, the principles weren&#8217;t too clear.  Suppose we decided to extend our <code>Foo</code> &#8220;class&#8221; - how exactly would this work?  First, you need to define the child type and then set its <code>prototype</code> value to a new object of the parent type.  An example:</p>
<pre><code>function FooChild(childName)
{
  Foo.call(this, 'I am a child of Foo and my name is ' + childName);
}
FooChild.prototype = new Foo('');

var fooChildObject = new FooChild('Barbar');
fooChildObject.getName(); // Will alert with 'I am a child of Foo and my name is Barbar'</code></pre>
<p>Let&#8217;s break down what&#8217;s going on here.</p>
<ol>
<li>
First, we define a new constructor called <code>FooChild</code>.  In it, we <code>call</code> the parent constructor function with the context set to the current object.  This allows the <code>name</code> property to be set on the object during creation since that&#8217;s what the parent does.
</li>
<li>
Then, we set the <code>prototype</code> property equal to a new object that&#8217;s an instance of <code>Foo</code>.  This is what allows all of the child objects to have access to the parent&#8217;s properties, such as the <code>getName()</code> method.
</li>
</ol>
<h3>A few more details</h3>
<p>JavaScript provides two special operators for dealing with types and objects.  One is called <code>instanceof</code> and the other is <code>typeof</code>.  The latter, <code>typeof</code>, is less useful since it only deals with built-in JavaScript types.</p>
<p>The <code>typeof</code> operator returns the current variable&#8217;s type, but is limited to predefined types.  For example, <code>typeof fooChildObject</code> or <code>typeof fooObject</code> both return a string with the contents of &#8220;object&#8221;.  Thus, differentiating between the two is impossible.  More information can be found <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Operators:Special_Operators:typeof_Operator">at the Mozilla Developer Center</a>.</p>
<p>The <code>instanceof</code> operator is more interesting.  It takes two arguments and tests whether the first is an instance of the second.  (I guess I didn&#8217;t need to explain that) For example:</p>
<pre><code>function Foo(name)
{
  this.name = name;
}
Foo.prototype.getName = function()
{
  alert(this.name);
}

function FooChild(childName)
{
  Foo.call(this, 'I am a child of Foo and my name is ' + childName);
}
FooChild.prototype = new Foo('');

var fooObject = new Foo('I am foo');
var fooChildObject = new FooChild('Barbar');

alert(fooChildObject instanceof Foo); // true
alert(fooObject instanceof Foo); // true
alert(fooChildObject instanceof FooChild); // true
alert(fooObject instanceof FooChild); // false;</code></pre>
<p>In the above code, it is clear that <code>fooChildObject</code> is an instance of <code>FooChild</code>, and <code>fooObject</code>is an instance of <code>Foo</code>.  However, <code>fooChildObject</code> <strong>is also</strong> an instance of <code>Foo</code>, since its type was inherited from it through the <code>prototype</code> property.  However, <code>fooObject</code> <strong>is not</strong> an instance of <code>FooChild</code> since that type is a child of <code>Foo</code>.</p>
<p>I hope I haven&#8217;t said &#8220;foo&#8221; one too many times for you.</p>
<p>More information about <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Property_Inheritance_Revisited:Determining_Instance_Relationships"><code>instanceof</code> is again available</a> from the excellent Mozilla Developer Center.</p>
<h3>Concluding remarks</h3>
<p>I hope this has helped you to understand the nature of JavaScript&#8217;s built-in inheritance features.  I know I found it very convoluted at first, coming from a class-inheritance background.  I read everything I could find on the subject, and I believe it&#8217;s made me a better JavaScript programmer by understanding some of the &#8220;inner workings&#8221; of the language.  I encourage you to check out some of the references I&#8217;ve provided below.</p>
<h3>References</h3>
<ol class="note less">
<li><a href="http://javascript.crockford.com/prototypal.html">Prototypal Inheritance in JavaScript</a> - Douglas Crockford</li>
<li><a href="http://20bits.com/2007/03/08/the-philosophy-of-javascript/">The Philosophy of JavaScript</a> - Jesse of 20bits</li>
<li><a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Property_Inheritance_Revisited">Prototype Inheritance Revisited</a> - Mozilla Developer Center</li>
<li><a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:The_Employee_Example">The Employee Example</a> - Mozilla Developer Center</li>
</ol>
<hr/>Copyright &copy; 2008 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/01/24/javascript-and-inheritance/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Using the &#8220;call&#8221; and &#8220;apply&#8221; methods to change the context of a function in JavaScript</title>
		<link>http://unitstep.net/blog/2007/12/18/using-the-call-and-apply-methods-to-change-the-context-of-a-function-in-javascript/</link>
		<comments>http://unitstep.net/blog/2007/12/18/using-the-call-and-apply-methods-to-change-the-context-of-a-function-in-javascript/#comments</comments>
		<pubDate>Wed, 19 Dec 2007 01:54:04 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[guides]]></category>

		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://unitstep.net/blog/2007/12/18/using-the-call-and-apply-methods-to-change-the-context-of-a-function-in-javascript/</guid>
		<description><![CDATA[In JavaScript, the context that function is executing in is very important.  What is context?  Basically, the context of a function is what object it is &#8220;attached&#8221; to - this object will be the reference of the &#8220;this&#8221; keyword within that function.  Every function has a context -that is to say, every [...]]]></description>
			<content:encoded><![CDATA[<p>In JavaScript, the context that function is executing in is very important.  What is context?  Basically, the context of a function is what object it is &#8220;attached&#8221; to - this object will be the reference of the &#8220;<code>this</code>&#8221; keyword within that function.  Every function has a context -that is to say, every function is attached to an object.  By default it is the <code>window</code> object.</p>
<p>You may have run into this particular aspect of JavaScript when working with event handlers.  For example:</p>
<pre><code>function alertId()
{
  alert (this.id);
}

document.getElementById('someId').onclick = alertId;</code></pre>
<p>This will return the &#8220;id&#8221; attribute of the element that the function has been attached to.  You could attach the same function to multiple objects and each time you called it on a different object, it would return a different value, since the context is different.  (Minor note: using <code>element.attachEvent()</code>, as part of the Microsoft event handler model, <a href="http://www.quirksmode.org/js/events_advanced.html">does not change the context</a> of the function so &#8220;<code>this</code>&#8221; will still refer to the <code>window</code> object)</p>
<p>However, there may be times when you want to change the meaning of <code>this</code> without actually having to attach that a function to an object.  Using the <code>call()</code> and <code>apply()</code> methods of the Function object can allow you to do this.</p>
<h3>Context is everything</h3>
<p>Let&#8217;s backtrack for a moment.  In JavaScript, many (but not all) variables are objects.  This includes the references to all functions as well - they are also objects.  In the example above, using &#8220;<code>alertId</code>&#8221; (<em>without</em> the parentheses) would refer to the <code>Function</code> object that represents <code>alertId</code>.  As the <code>Function</code> object is a predefined object in JavaScript, it has <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Function">methods and properties associated</a> with it.</p>
<p>Two of these methods are <code>call()</code> and <code>apply()</code>.  Using these methods on a Function object allows you to set the context of that function - that is, what the &#8220;<code>this</code>&#8221; keyword refers to.  The two only in how arguments are passed to the function whose context is being redefined.  For example <code>apply()</code> takes an array of arguments like this:</p>
<pre><code>function someFunction(arg1, arg2)
{
  this.id = arg1 + arg2;
}

var arrayOfArguments = ['valueOfArg1', 'valueOfArg2'];

someFunction.apply(objectToBeUsedAsThis, arrayOfArguments);</code></pre>
<p>The values in the second-argument array are then used as the arguments to the <code>someFunction()</code> function.  </p>
<p>The <code>call()</code> method is almost the same except it does not take an array of arguments, but rather just an indeterminate number of arguments that are all passed to the function.  For example, the above could also be accomplished with this code:</p>
<pre><code>function someFunction(arg1, arg2)
{
  this.id = arg1 + arg2;
}

someFunction.call(objectToBeUsedAsThis, 'valueOfArg1', 'valueOfArg2');</code></pre>
<p>I prefer to use <code>apply()</code> sometimes since you can directly use the <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Function:arguments"><code>arguments</code></a> variable that is local within all functions. (The variable <code>arguments</code> stores all the arguments that were passed to the function when it was called, and so this can be used in a situation with where it is desired to have a function with a variable number of arguments.)</p>
<h3>A useful example</h3>
<p>So far, the examples posed have been fairly trivial.  Let&#8217;s look at a real-world use of <code>call()</code> to illustrate its usefulness.  Remember the <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Function:arguments"><code>arguments</code></a> variable?  Basically, you have access to this object variable whenever you&#8217;re inside a function since it stores all the arguments passed to this function.  However, it&#8217;s not exactly an array (although it works like one sometimes) and thus it <em>does not</em> have access to <code>Array</code> methods such as <a href="http://www.devguru.com/Technologies/ecmaScript/quickref/join.html"><code>join()</code></a>.  </p>
<p>We could easily convert it into an array by accessing each property by its index using a loop, but there&#8217;s an easier to way to do this.  Consider the following code:</p>
<pre><code>function someFunction()
{
  var argsArray = Array.prototype.slice.call(arguments, 0);
}</code></pre>
<p>Using this one line, we have successfully converted the <code>arguments</code> into a true Array object and stored the result in the <code>argsArray</code> variable.  How?  First, we access the <a href="http://www.devguru.com/Technologies/ecmaScript/quickref/slice.html"><code>slice()</code></a> method on the <code>Array</code> object through the <code>prototype</code> property and then <code>call()</code> the method telling it to use the <code>arguments</code> object as <code>this</code>.</p>
<p>The <code>slice()</code> method allows us to extract a section of an existing array.  However, by using <code>call()</code> we are able to apply its effects on the <code>arguments</code> object that is similar to, but not exactly an <code>Array</code> object.  The second argument of &#8216;0&#8242; merely indicates that we want to extract not just a part of <code>arguments</code> but all of it.  Since <code>slice()</code> always returns an <code>Array</code> object, we thus get back a true array containing the same data as the <code>arguments</code> object.  And that&#8217;s it!</p>
<p>Note that the above example could be compacted even further.  However, it looks very cryptic and can be confusing. (As if the previous example wasn&#8217;t confusing enough!) </p>
<pre><code>function someFunction()
{
  var argsArray = [].slice.call(arguments);
}</code></pre>
<p>This example works the same as the previous one.  Instead of using <code>Array.prototype</code>, we create a &#8216;dummy&#8217; empty array to get access to the <code>slice()</code> method.  The second argument of &#8216;0&#8242; isn&#8217;t needed, as if it is left out when using <code>slice()</code> the entire contents will be returned.</p>
<h3>Contextual Conclusion</h3>
<p>In short, using these methods to change the scope of a function can allow you to do some neat things with JavaScript that aren&#8217;t possible in some other languages.  However, one should always be mindful to keep code readable and maintainable and to lessen the learning curve for those new to a language.</p>
<hr/>Copyright &copy; 2008 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2007/12/18/using-the-call-and-apply-methods-to-change-the-context-of-a-function-in-javascript/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Exception handling in JavaScript</title>
		<link>http://unitstep.net/blog/2007/11/25/exception-handling-in-javascript/</link>
		<comments>http://unitstep.net/blog/2007/11/25/exception-handling-in-javascript/#comments</comments>
		<pubDate>Mon, 26 Nov 2007 01:54:00 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[exceptions]]></category>

		<category><![CDATA[guides]]></category>

		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://unitstep.net/blog/2007/11/25/exception-handling-in-javascript/</guid>
		<description><![CDATA[Exception handling is a topic that may not be well-understood by some web developers, depending on what languages they have the most experience in.  In particular, PHP, one of the most common server-side languages for web development, did not have support for exception handling until version 5.  In the four years between the [...]]]></description>
			<content:encoded><![CDATA[<p>Exception handling is a topic that may not be well-understood by some web developers, depending on what languages they have the most experience in.  In particular, <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym>, one of the most common server-side languages for web development, did not have support for exception handling until <a href="http://www.php.net/exceptions">version 5</a>.  In the four years between the release of PHP4 and PHP5, the language became increasingly popular among developers, and as a result, a lot of code was written without exception handling in mind.  The situation did not even improve much with the release of PHP5, since PHP5 was meant to be backwards-compatible with code developed for PHP4.  Three years later, there are still <a href="http://www.gophp5.org/">movements</a> to get developers to transition to a purely-PHP5 model.</p>
<p>Some of this may have transferred over to JavaScript, a language that is already poorly understood and often implemented even worse.  It is often hard to find well-written, maintainable JavaScript code, as it is often left as an afterthought in a project or otherwise not given much consideration, having been delegated to the realm of popup scripts and mouse-overs.  While exception handling may be overkill for a lot of JavaScript applications, many do not even know of JavaScript&#8217;s exception-handling capabilities.  In this article, I&#8217;ll give a brief overview of exception handling and some recommendations on how to use it in JavaScript to improve the readability of code. </p>
<h2>Exceptional conditions</h2>
<p>I won&#8217;t go too in-depth about the <a href="http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.html">merits of using exception handling</a> but will instead just give a brief overview.  (While there are some drawbacks, these apply more to the Java language rather than JavaScript)</p>
<p>The main reason for using exceptions is to have a separate channel for communicating errors.  Without this, you must communicate error conditions using the function itself. Consider a function that performs mathematical division:</p>
<pre><code>function divide(dividend, divisor)
{
  var quotient = dividend/divisor;
  return quotient;
}</code></pre>
<p>Division is a fairly simple arithmetic operation, but of the four basic operations it is the only one that has limits on its arguments: the divisor (the term you divide by) cannot be zero, since <a href="http://en.wikipedia.org/wiki/Division_%28mathematics%29">division by zero is undefined.</a>  So, how should you handle cases where the supplied arguments result in division by zero?  (The situation is very likely in an application accepting user input)</p>
<p>Without using exceptions, you have a few options, each of which has its own weaknesses.  Firstly, you could choose not to return <em>anything</em> and just <code>alert()</code> the user of the error.  This isn&#8217;t good since when you call the <code>divide()</code> function, you expect a result, not a warning message.</p>
<p>Secondly, you could choose to return a special &#8220;error code&#8221; indicating that there was a division by zero.  But this creates another problem - what exactly <em>do</em> you return when something goes wrong?  In this case, the only error case is division by zero - since JavaScript is a weakly-typed language, you could just return <code>false</code> on this error, but then in the calling code you&#8217;d have to check if <code>divide()</code> equaled <code>false</code> before using it, probably using the <a href="http://www.webreference.com/js/column26/stricteq.html">strict equality operator</a>.  As you can see, things get messy fast. </p>
<p>Alternatively, you could just check the inputs/arguments every time before you called the function.  However this is clumsy, and adds another layer of complexity where something could go wrong.  </p>
<h2>Another way of doing things</h2>
<p>As mentioned before, exception handling adds a side channel of sorts strictly for communicating errors.  By doing this, it allows for the interruption of program flow for the purpose of dealing with the exception or error situation.  Using exceptions, you would re-write the function above like this:</p>
<pre><code>function divide(dividend, divisor)
{
  if (0 == divisor) {
    throw new Error("Bzlorg! Cannot divide by zero.");
  }

  var quotient = dividend/divisor;
  return quotient;
}</code></pre>
<p>Here we are checking if the divisor equals zero - signifying an invalid input value - and then throwing an exception if this is the case.  How is this different than returning an error code?</p>
<p>The main difference is in the <em>control flow</em> of the program; using exceptions causes a change in the program flow.  In the above example, if the divisor equals zero, the execution of the function stops there and returns to the calling code with the throw exception.  The subsequent statements calculating the quotient and returning will not be executed.  Here&#8217;s an example of how you&#8217;d call the <code>divide</code> function.</p>
<pre><code>try {
  var dividend = 3;
  var divisor = 0;

  var quotient = divide(dividend, divisor);

  alert("The answer is " + quotient);
}
catch (e) {
  alert(e.message);
}</code></pre>
<p>With exceptions, you enclose code that could throw an exception with a <code>try</code> block.  This signifies to the interpreter (in the case of JavaScript) that you will be executing code (in this case, calling a function) that <em>could</em> throw an exception as a result of some error condition.  Thus you are <code>try</code>ing to do something - but as in real life, things may go wrong.</p>
<p>In this example, everything works until the line calling <code>divide</code>.  Since <code>divide</code> throws an exception with the input values supplied, flow will be directed to the <code>catch</code> block.  All <code>try</code> blocks must be followed with a <code>catch</code> block, with the variable in the parentheses specifying the variable to hold the thrown exception object.  In the code above, we merely alert the user to the problem - the message &#8220;Bzlorg! Cannot divide by zero&#8221; is displayed - in a real program you most likely would want to do handle the error differently depending on the context - but that&#8217;s a whole different topic.</p>
<p>If, however, you executed the code with valid values and no exceptions were thrown, once the program had got to the end of the <code>try</code> block it would jump over the following <code>catch</code> block and the user would be alerted with the correct answer.  Code within a <code>catch</code> block is <em>only</em> executed in the event that an exception is thrown.</p>
<h3>Differences with Java</h3>
<p>Since Java is an extremely popular language and one that also uses a similar exception handling model, it would be prudent to discuss some of the differences and similarities with it and JavaScript.</p>
<ol>
<li>
<h4><del>No multiple catch blocks with JavaScript</del></h4>
<p><del>This is perhaps the biggest difference.  If you&#8217;re familiar with Java you&#8217;ll know that different exception objects can be thrown during execution (all subclasses of the root/parent <code>Exception</code> class defined by Java), each signifying different error conditions.  You catch each of them separately by using separate catch blocks, each specifying a particular class or parent class.  However, with JavaScript, as you might have noticed from the code above, there can only be one catch block and thus there&#8217;s no need to specify the exception class. </del></p>
<p><del>If, however, you want the granularity of working with different exception classes, you&#8217;ll have to use the <code>instanceof</code> operator within a catch block, like this:</del></p>
<pre><code>try {
  ...
}
catch (e) {
  if (e instanceof RangeError) {
    ...
  }
  else if (e instanceof TypeError) {
    ...
   }
}</code></pre>
<p><del>It&#8217;s not as elegant as having multiple catch blocks, but it&#8217;s one way to deal with multiple exception types.</del></p>
<h4>Correction:</h4>
<p>It appears I was mistaken.  In JavaScript, you can indeed have <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Exception_Handling_Statements:try...catch_Statement#The_catch_Block">multiple catch blocks</a>, as seen in the <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide">Core JavaScript 1.5 Guide</a> from the Mozilla Developer Center.  My initial example above is still valid syntactically, but this way may be more appealing.  An example is as follows:</p>
<pre><code>try {
  ...
}
catch (e if e instanceof RangeError) {
  ...
}
catch (e if e instanceof TypeError) {
  ...
}
catch (e) {
  // General catch-all block.
  ...
}</code></pre>
<p>It just goes to show that when you think you know something, you probably don&#8217;t!  This is part of why I like JavaScript (and by extension, programming); there&#8217;s always more to learn and experience to be gained.</p>
</li>
<li>
<h4>Exception types</h4>
<p>The discussion of exception types brings us to another point - the different exception types in JavaScript.  JavaScript defines some <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Error">built-in exception</a> types, all based off the parent <code>Error</code> object.  These should suffice for most situations where you&#8217;re checking user input (the most common use), but if you&#8217;re developing a complex application you may want to define your own.  </p>
<p>In that situation, things get a little tricky, especially if you&#8217;re coming from Java.  Despite the outward similarity, JavaScript does not uses classes like Java, but instead uses a <a href="http://en.wikipedia.org/wiki/Prototype-based_programming">prototype-based approach</a> where inheritance comes from existing objects.  In this respect, things can get complicated as there are debates on <a href="http://www.sitepoint.com/blogs/2006/01/17/javascript-inheritance/">what the best way to inherit from objects</a> is and to that degree, a few JavaScript libraries have been written to facilitate the extending of objects in JavaScript.  These points are beyond the scope of this article, but I thought I&#8217;d just point you in the right direction.</p>
<p>Interestingly, you can also <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Exception_Handling_Statements:throw_Statement">throw many different</a> types of expressions, and are not limited to the built-in exception types.  For example, <code>throw false;</code> and <code>throw "Hello World";</code> are valid statements, but in my opinion, it doesn&#8217;t make much sense to throw any type of expression just because you can.  Using the built-in exception types (or defining your own) is a better practice, though throwing just String expressions might be alright in some situations.
</li>
<li>
<h4>Runtime errors</h4>
<p>During execution, you code may trigger runtime errors within JavaScript - for example, when trying to reference a property on a non-existent object.  These will also result in a new <code>Error</code> object being thrown, even though you did not define this throw in your code.  If this happens within a try block, the exception will subsequently be caught in the following catch block, and if you&#8217;re not expecting this error you may miss it.  (If, for example, you&#8217;re only looking for specific exception object types)</p>
<p>This can create problems with some of the JavaScript debuggers out there like <a href="http://www.getfirebug.com">Firebug</a>.  Since the runtime exception is being caught, Firebug will not be able to catch it (it is prevented from &#8220;filtering&#8221; up), so you may not be able to locate the source of your error if you&#8217;re relying on the debugger.  </p>
<p>My recommendation is thus to ensure your code runs properly under normal conditions.  Only then should you start using exceptions and try-catch statements.  This will ensure that no unexpected runtime exceptions get caught.  (The runtime errors are analogous to the unchecked runtime exceptions of Java in that they are not normally caught)
</li>
</ol>
<h3>Summing it up</h3>
<p>The whole point of using exceptions is not to make your code &#8220;work&#8221; better - anything that can be accomplished with exceptions can most likely be done without it, with just the same end result.  The point is to make your code more readable, manageable and flexible.  By using exceptions you get rid of having to use cumbersome &#8220;error codes&#8221;, the values of which you may forget later.  You also get more flexibility with how you handle errors.  You need not handle the error right in the function where it occurs - you can throw an exception to the calling code and handle the error there - or, alternatively, you could let the exception bubble up to a higher-level and handle all errors there.  It really depends on your needs, but using exceptions allows for this to be implemented more readily.</p>
<p>Though exceptions may seem like overkill for JavaScript and despite the limitations of its exception handling model as compared to that of Java&#8217;s, there are still some benefits to using exceptions, especially for complex JavaScript applications that you may implement to improve the interactivity of your site. </p>
<h4>Changes/Fixes</h4>
<ul>
<li><strong>2007-12-06</strong>: Changed <code>throw new Exception(...)</code> to correct statement of <code>throw new Error(...)</code>.</li>
<li><strong>2008-01-08</strong>: Fixed incorrect assertion of &#8220;No Multiple Catch Blocks&#8221; in JavaScript; added remarks about being able to throw any type of expression.</li>
</ul>
<hr/>Copyright &copy; 2008 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2007/11/25/exception-handling-in-javascript/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
