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

<channel>
	<title>Elegant Code &#187; JavaScript</title>
	<atom:link href="http://elegantcode.com/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Sun, 12 Feb 2012 04:40:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.5</generator>
		<item>
		<title>Resources for getting started with Backbone.js</title>
		<link>http://elegantcode.com/2012/01/23/resources-for-getting-started-with-backbone-js/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=resources-for-getting-started-with-backbone-js</link>
		<comments>http://elegantcode.com/2012/01/23/resources-for-getting-started-with-backbone-js/#comments</comments>
		<pubDate>Tue, 24 Jan 2012 05:34:43 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Backbone.js]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2012/01/23/resources-for-getting-started-with-backbone-js/</guid>
		<description><![CDATA[The current product I am building makes heavy use of HTML5 &#38; javascript to give the user a rich experience, both on and offline, across a variety of screens. Before I even started this application I knew I wanted a clean and proven approach to help manage the complexity on the client. After reviewing several [...]]]></description>
			<content:encoded><![CDATA[<p>The current product I am building makes heavy use of HTML5 &amp; javascript to give the user a rich experience, both on and offline, across a variety of screens. Before I even started this application I knew I wanted a clean and proven approach to help manage the complexity on the client. After reviewing several js frameworks I decided to go with backbone.js (<a href="http://addyosmani.github.com/todomvc/">compare yourself</a>). I have been working with backbone for several months and I am really happy with it, and would recommend to anyone building similar types of javascript applications.</p>
<p>As per the project description:</p>
<p><i>“</i><a href="http://github.com/documentcloud/backbone/"><i>Backbone</i></a><i> </i><i>supplies structure to JavaScript-heavy applications by providing <b>models </b>with key-value binding and custom events, <b>collections</b> with a rich API of enumerable functions, <b>views</b> with declarative event handling, and connects it all to your existing application over a RESTful JSON interface.”</i></p>
<p>There are a ton of good ‘getting started’ posts out there, so rather than duplicate those I thought I would put together a few of my favorite resources. Hopefully some of you might find them useful.</p>
<ul>
<li><a href="http://documentcloud.github.com/backbone/">Backbone.js</a> : The main github site- Here you will find valuable reference documentation as well a simple examples to introduce you to backbone. Be prepared to spend a little time here <img src='http://elegantcode.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  </li>
<li><a href="http://documentcloud.github.com/underscore/">Underscore.js</a> : “<i>It&#8217;s the tie to go along with <a href="http://docs.jquery.com/">jQuery</a></i><i>&#8216;s tux, and <a href="http://backbonejs.org/">Backbone.js</a></i><i>&#8216;s suspenders.”&#160; </i>If you haven&#8217;t heard about underscore do yourself a favor on go check it out. There is nothing magical about it, yet I can’t say enough. Even if you aren’t using backbone, I highly recommend this library (some folks are using it on the server with node.js as well). </li>
<li><a href="http://documentcloud.github.com/backbone/docs/todos.html">Todo.js</a> : A simple Todo list example using backbone.js </li>
<li><a href="http://addyosmani.github.com/todomvc/">TodoMVC</a> : Compare a truck load of JS MVC frameworks – <em>“a project which offers the same Todo application implemented using MVC concepts in most of the popular JavaScript MVC frameworks of today.”</em> </li>
<li><a href="https://github.com/addyosmani/backbone-fundamentals">Backbone.js Fundamentals</a> : A book on Backbone.js targeted at beginners and advanced users alike &#8211; by <a href="http://twitter.com/addyosmani">Addy Osmani</a> (and <a href="https://github.com/addyosmani/backbone-fundamentals/contributors">contributors</a>). This guide is quickly becoming the ‘mini-bible’ for backbone. Chalked full of nuggets, from beginning concepts to the more advanced. </li>
<li><a href="http://weblog.bocoup.com/introducing-the-backbone-boilerplate/">The Backbone Boilerplate</a> : <em>“Backbone Boilerplate is a set of best practices and utilities for building Backbone.js applications”</em> </li>
<li><a href="http://weblog.bocoup.com/organizing-your-backbone-js-application-with-modules/">Organizing Your Backbone.js Application With Modules</a> : Some guidance around how you might structure your application using modules (esp valuable for larger applications). </li>
<li><a href="http://backbonetutorials.com/organizing-backbone-using-modules/">Organizing your application using Modules (require.js)</a> : Similar to the previous article, but makes use of AMD &amp; Require.js to wire up the application. </li>
<li><a href="http://lostechies.com/derickbailey/category/backbone/">Derick Baileys blog on Lostechies</a> : Derick has been blogging on backbone for 6 mos or so. I appreciate reading Dericks blog because he has done such a good job of cataloging his experiences as he has learned the framework. When I found myself stumbling with backbone, my searches often led over to Dericks blog. </li>
<li><a href="http://joeybeninghove.com/2011/08/16/backbone-screencast-introduction-views/">Backbone.js Screencast &#8211; Introduction and Views</a> : A nice “<em>basic introduction on how to bootstrap a new Backbone.js application and go in-depth on how to use Backbone Views in particular”.</em> Joey now also has screencasts available over at his site <a href="http://backbonescreencasts.com/">http://backbonescreencasts.com/</a> </li>
<li><a href="http://www.youtube.com/watch?v=258gBoR734U">Backbone.js walkthrough of Models and Views (Part 1/2) Screencast :</a> Enough said! </li>
<li>Using node.js + backbone.js + socket.io for real-time goodness : I haven&#8217;t actually implemented this yet, but am excited about the <a href="http://blog.fogcreek.com/the-trello-tech-stack/">possibilities</a>. Check out <a href="http://developer.teradata.com/blog/jasonstrimpel/2011/11/backbone-js-and-socket-io">here</a> <a href="http://fzysqr.com/2011/02/28/nodechat-js-using-node-js-backbone-js-socket-io-and-redis-to-make-a-real-time-chat-app/">here</a> and <a href="http://andyet.net/blog/2011/feb/15/re-using-backbonejs-models-on-the-server-with-node/">here</a> for some examples. (seeing how the middle tier in this app is MVC.net, I may opt to swap socket.io for <a href="https://github.com/SignalR/SignalR">signalR</a>. Hoping to take the node.js plunge at some point). </li>
</ul>
<p><strong>Updated:</strong></p>
<ul>
<li><a href="http://backbonetraining.net/resources">http://backbonetraining.net/resources</a> : Excellent collection of resources</li>
<li><a href="http://recipeswithbackbone.com/">http://recipeswithbackbone.com/</a> : Strategies to accelerate development      <br />with Backbone.js ($24 e-book)</li>
</ul>
<p>That’s all for now. Please feel free to reach out with any other resources you found helpful and Ill add them on here. I am still very much learning and would love to read your posts. More to come-</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2012/01/23/resources-for-getting-started-with-backbone-js/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Basic JavaScript Part 12: Function Hoisting</title>
		<link>http://elegantcode.com/2011/03/24/basic-javascript-part-12-function-hoisting/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=basic-javascript-part-12-function-hoisting</link>
		<comments>http://elegantcode.com/2011/03/24/basic-javascript-part-12-function-hoisting/#comments</comments>
		<pubDate>Thu, 24 Mar 2011 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2011/03/24/basic-javascript-part-12-function-hoisting/</guid>
		<description><![CDATA[Here are the links to the previous installments: Functions Objects Prototypes Enforcing New on Constructor Functions Hoisting Automatic Semicolon Insertion Static Properties and Methods Namespaces Reusing Methods of Other Objects &#160; The Module Pattern &#160; Functional Initialization In a previous post I already discussed the phenomenon of hoisting in JavaScript. In that post I showed [...]]]></description>
			<content:encoded><![CDATA[<p>Here are the links to the previous installments:</p>
<ol>
<li><a href="http://elegantcode.com/2010/10/22/basic-javascript-part-1-functions/" target="_blank">Functions</a></li>
<li><a href="http://elegantcode.com/2010/11/12/basic-javascript-part-2-objects/" target="_blank">Objects</a></li>
<li><a href="http://elegantcode.com/2010/12/03/basic-javascript-part-3-prototypes/" target="_blank">Prototypes</a></li>
<li><a href="http://elegantcode.com/?p=4015" target="_blank">Enforcing New on Constructor Functions</a></li>
<li><a href="http://elegantcode.com/2010/12/24/basic-javascript-part-5-hoisting/" target="_blank">Hoisting</a></li>
<li><a href="http://elegantcode.com/2011/01/12/basic-javascript-part-6-automatic-semicolon-insertion/" target="_blank">Automatic Semicolon Insertion</a></li>
<li><a href="http://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/" target="_blank">Static Properties and Methods</a></li>
<li><a href="http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/" target="_blank">Namespaces</a></li>
<li><a href="http://elegantcode.com/2011/01/31/basic-javascript-part-9-reusing-methods-of-other-objects/" target="_blank">Reusing Methods of Other Objects</a></li>
<li>&#160; <a href="http://elegantcode.com/2011/02/15/basic-javascript-part-10-the-module-pattern/" target="_blank">The Module Pattern</a></li>
<li>&#160; <a href="http://elegantcode.com/2011/03/04/basic-javascript-part-11-functional-initialization/" target="_blank">Functional Initialization</a></li>
</ol>
<p align="justify">In a <a href="http://elegantcode.com/2010/12/24/basic-javascript-part-5-hoisting/" target="_blank">previous post</a> I already discussed the phenomenon of hoisting in JavaScript. In that post I showed the effects of variable hoisting and why it’s important to declare all variables at the top of a function body. For this post I want to briefly focus on function hoisting. Let’s start off with an example to illustrate this concept.</p>
<pre class="csharpcode">functionExpression();        <span class="rem">// undefined</span>
functionDeclaration();        <span class="rem">// &quot;Function declaration called.&quot;        </span>

<span class="kwrd">var</span> functionExpression = <span class="kwrd">function</span>() {
    console.log(<span class="str">'Function expression called.'</span>);
};

functionExpression();        <span class="rem">// &quot;Function expression called.&quot;</span>
functionDeclaration();        <span class="rem">// &quot;Function declaration called.&quot;</span>

<span class="kwrd">function</span> functionDeclaration() {
    console.log(<span class="str">'Function declaration called.'</span>);
}

functionExpression();        <span class="rem">// &quot;Function expression called.&quot;</span>
functionDeclaration();        // <span class="str">&quot;Function declaration called.&quot;</span></pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p align="justify">In order to understand what’s going on here, we first need to understand the distinction between a function expression and a function declaration. As it’s name implies, a function expression defines a function as part of an expression (in this case assigning it to a variable). These kind of functions can either be anonymous or they can have a name.</p>
<pre class="csharpcode"><span class="rem">// </span>
<span class="rem">// Anonymous function expression</span>
<span class="rem">//</span>
<span class="kwrd">var</span> functionExpression = <span class="kwrd">function</span>() {
    console.log(<span class="str">'Function expression called.'</span>);
};

<span class="rem">// </span>
<span class="rem">// Named function expression</span>
<span class="rem">//</span>
<span class="kwrd">var</span> functionExpression = <span class="kwrd">function</span> myFunctionExpression() {
    console.log(<span class="str">'Function expression called.'</span>);
};</pre>
<p align="justify">On the other hand, a function declaration is always defined as a named function without being part of any expression. </p>
<p align="justify">So, for the example shown earlier, the function expression can only be called after it has been defined while the function declaration can be executed both before and after it’s definition. Let’s look at how JavaScript actually interprets this code in order to explain why it behaves that way.</p>
<pre class="csharpcode"><span class="kwrd">var</span> functionExpression,        <span class="rem">// undefined</span>
    functionDeclaration =  <span class="kwrd">function</span>() {
        console.log(<span class="str">'Function declaration called.'</span>);
     };

functionExpression();        <span class="rem">// Still undefined</span>
functionDeclaration();        <span class="rem">// &quot;Function declaration called.&quot;        </span>

<span class="rem">// The assignment expression is still left at the original location</span>
<span class="rem">// although the variable declaration has been moved to the top. </span>
functionExpression = <span class="kwrd">function</span>() {
    console.log(<span class="str">'Function expression called.'</span>);
};

functionExpression();        <span class="rem">// &quot;Function expression called.&quot;</span>
functionDeclaration();        <span class="rem">// &quot;Function declaration called.&quot;</span>

<span class="rem">// Here we originally defined our function declaration</span>
<span class="rem">// which has been completely moved to the top.</span>

functionExpression();        <span class="rem">// &quot;Function expression called.&quot;</span>
functionDeclaration();        // <span class="str">&quot;Function declaration called.&quot;</span></pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p align="justify">JavaScript turns our function declaration into a function expression and hoists it to the top. Here we see the same thing happening to our function expression as I explained in the previous post on variable hoisting. This also explains why the first call of our function expression results in an error being thrown because the variable is undefined.&#160;&#160; </p>
<p align="justify">So basically, JavaScript applies different rules when it comes to function hoisting depending on whether you have a function expression or a function declaration. A function declaration is fully hoisted while a function expression follows the same rules as variable hoisting. It definitely took me a while to wrap my head around this.</p>
<p align="justify">Until next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2011/03/24/basic-javascript-part-12-function-hoisting/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Basic JavaScript Part 11: Functional Initialization</title>
		<link>http://elegantcode.com/2011/03/04/basic-javascript-part-11-functional-initialization/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=basic-javascript-part-11-functional-initialization</link>
		<comments>http://elegantcode.com/2011/03/04/basic-javascript-part-11-functional-initialization/#comments</comments>
		<pubDate>Sat, 05 Mar 2011 00:57:21 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2011/03/04/basic-javascript-part-11-functional-initialization/</guid>
		<description><![CDATA[Here are the links to the previous installments: Functions Objects Prototypes Enforcing New on Constructor Functions Hoisting Automatic Semicolon Insertion Static Properties and Methods Namespaces Reusing Methods of Other Objects &#160;The Module Pattern I just want to quickly share some beautiful JavaScript code I picked up while watching the most excellent screencast 11 More Things [...]]]></description>
			<content:encoded><![CDATA[<p>Here are the links to the previous installments:</p>
<ol>
<li><a href="http://elegantcode.com/2010/10/22/basic-javascript-part-1-functions/">Functions</a></li>
<li><a href="http://elegantcode.com/2010/11/12/basic-javascript-part-2-objects/">Objects</a></li>
<li><a href="http://elegantcode.com/2010/12/03/basic-javascript-part-3-prototypes/">Prototypes</a></li>
<li><a href="http://elegantcode.com/?p=4015">Enforcing New on Constructor Functions</a></li>
<li><a href="http://elegantcode.com/2010/12/24/basic-javascript-part-5-hoisting/">Hoisting</a></li>
<li><a href="http://elegantcode.com/2011/01/12/basic-javascript-part-6-automatic-semicolon-insertion/">Automatic Semicolon Insertion</a></li>
<li><a href="http://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/">Static Properties and Methods</a></li>
<li><a href="http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/">Namespaces</a></li>
<li><a href="http://elegantcode.com/2011/01/31/basic-javascript-part-9-reusing-methods-of-other-objects/">Reusing Methods of Other Objects</a></li>
<li>&#160;<a href="http://elegantcode.com/2011/02/15/basic-javascript-part-10-the-module-pattern/" target="_blank">The Module Pattern</a></li>
</ol>
<p align="justify">I just want to quickly share some beautiful JavaScript code I picked up while watching the most excellent screencast <a href="http://paulirish.com/2011/11-more-things-i-learned-from-the-jquery-source/" target="_blank">11 More Things I Learned from the jQuery Source</a> by <a href="http://paulirish.com/" target="_blank">Paul Irish</a>.</p>
<pre class="csharpcode"><span class="kwrd">var</span> <span class="kwrd">base</span> = dom.getElementByTagName(<span class="str">'base'</span>)[0] | | (<span class="kwrd">function</span>() {
     <span class="rem">// Do some stuff</span>
     <span class="kwrd">return</span> someElement.insertBefore(dom.createElement(<span class="str">'base'</span>), someElement.firstChild) ;
})(); </pre>
<p align="justify">
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This single line of code basically checks whether there’s a <a href="http://www.w3schools.com/TAGS/tag_base.asp" target="_blank">base tag</a> somewhere in the DOM. If there is one, then it assigns the reference for the first element to the <em>base</em> variable. If it’s not in the there, then a self-executing function inserts a new base tag into the DOM and returns the reference to the new element. </p>
<p align="justify">I don’t know about you, but I think this is pretty neat.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2011/03/04/basic-javascript-part-11-functional-initialization/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Basic JavaScript Part 10: The Module Pattern</title>
		<link>http://elegantcode.com/2011/02/15/basic-javascript-part-10-the-module-pattern/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=basic-javascript-part-10-the-module-pattern</link>
		<comments>http://elegantcode.com/2011/02/15/basic-javascript-part-10-the-module-pattern/#comments</comments>
		<pubDate>Tue, 15 Feb 2011 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2011/02/15/basic-javascript-part-10-the-module-pattern/</guid>
		<description><![CDATA[Here are the links to the previous installments: Functions Objects Prototypes Enforcing New on Constructor Functions Hoisting Automatic Semicolon Insertion Static Properties and Methods Namespaces Reusing Methods of Other Objects The module pattern is quite popular in the JavaScript community as is heavily applied by many JavaScript developers. There’s also the CommonJS initiative, which defines [...]]]></description>
			<content:encoded><![CDATA[<p>Here are the links to the previous installments:</p>
<ol>
<li><a href="http://elegantcode.com/2010/10/22/basic-javascript-part-1-functions/" target="_blank">Functions</a></li>
<li><a href="http://elegantcode.com/2010/11/12/basic-javascript-part-2-objects/" target="_blank">Objects</a></li>
<li><a href="http://elegantcode.com/2010/12/03/basic-javascript-part-3-prototypes/" target="_blank">Prototypes</a></li>
<li><a href="http://elegantcode.com/?p=4015" target="_blank">Enforcing New on Constructor Functions</a></li>
<li><a href="http://elegantcode.com/2010/12/24/basic-javascript-part-5-hoisting/" target="_blank">Hoisting</a></li>
<li><a href="http://elegantcode.com/2011/01/12/basic-javascript-part-6-automatic-semicolon-insertion/" target="_blank">Automatic Semicolon Insertion</a></li>
<li><a href="http://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/" target="_blank">Static Properties and Methods</a></li>
<li><a href="http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/" target="_blank">Namespaces</a></li>
<li><a href="http://elegantcode.com/2011/01/31/basic-javascript-part-9-reusing-methods-of-other-objects/" target="_blank">Reusing Methods of Other Objects</a></li>
</ol>
<ol>The module pattern is quite popular in the JavaScript community as is heavily applied by many JavaScript developers. There’s also the <a href="http://www.commonjs.org/">CommonJS</a> initiative, which defines a specification for a common set of JavaScript API’s that are organized using self-contained modules. These specifications are supported by a growing community as they provide the foundation for the <a href="http://www.dzone.com/links/r/taking_baby_steps_with_nodejs_commonjs_and_creati.html" target="_blank">modules that are built into Node.js</a> and numerous other open-source JavaScript libraries. This pattern has become so widespread because it’s an excellent way to package and organize an independent, self-containing piece of JavaScript code. The module pattern is composed by using <a href="http://elegantcode.com/2010/10/22/basic-javascript-part-1-functions/" target="_blank">self-executing functions</a> combined with <a href="http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/" target="_blank">namespaces</a>. Let’s show a simple example.
<pre class="csharpcode"><span class="kwrd">namespace</span>(<span class="str">'media'</span>);

media.podcast = (<span class="kwrd">function</span>(name) {
    <span class="kwrd">var</span> fileExtension = <span class="str">'mp3'</span>;        

    <span class="kwrd">function</span> determineFileExtension() {
        console.log(<span class="str">'File extension is of type '</span> + fileExtension);
    }

    <span class="kwrd">return</span> {
        download: <span class="kwrd">function</span>(episode) {
            console.log(<span class="str">'Downloading '</span> + episode + <span class="str">' of '</span> + name);
            determineFileExtension();
        }
    }
}(<span class="str">'Astronomy podcast'</span>));</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>First we define a namespace called <em>media</em>. Then we use a self-executing function that returns an anonymous object with a method named <em>download</em> that can be invoked by external code. Inside the self-executing function we have a variable <em>fileExtension</em> and a function <em>determineFileExtension</em> that are private and can only be used inside the <em>module</em>. Notice that we provide a fixed parameter value for the self-executing function. This technique is usually applied to pass in some kind of global object. <a href="https://github.com/jquery" target="_blank">jQuery</a> uses this same approach to <a href="https://github.com/jquery/jquery/blob/master/src/core.js" target="_blank">inject a reference to the global window object</a> into the scope of its module. </ol>
<ol>We can use the <em>download</em> method of our module like so …</p>
<pre class="csharpcode">media.podcast.download(<span class="str">'the first episode'</span>);</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>… which outputs what we expect:</p>
<blockquote style="margin-right: 0px" dir="ltr">
<p><em>Downloading the first episode of Astronomy podcast</em></p>
<p><em>File extension is of type mp3</em></p>
</blockquote>
<p>The way we implemented the module pattern here has at least one major downside. We’re able to completely replace the implementation of the <em>download</em> method that is exported by the anonymous object returned from the self-executing function. This can become quite troublesome if we have other functions inside our module that also make use of the <em>download</em> method and thereby rely on its functionality. The way to fix this issue is to make all functions private and export them using the anonymous object: </ol>
<ol>
<pre class="csharpcode"><span class="kwrd">namespace</span>(<span class="str">'media'</span>);

media.podcast = (<span class="kwrd">function</span>(name) {
    <span class="kwrd">var</span> fileExtension = <span class="str">'mp3'</span>;        

    <span class="kwrd">function</span> determineFileExtension() {
        console.log(<span class="str">'File extension is of type '</span> +fileExtension);
    }

    <span class="kwrd">function</span> download(episode) {
        console.log(<span class="str">'Downloading '</span> + episode + <span class="str">' of '</span> + name);
        determineFileExtension();
    }

    <span class="kwrd">return</span> {
        download: download
    }
}(<span class="str">'Astronomy podcast'</span>));</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</ol>
<ol>The <em>download</em> method exposed by the anonymous object can still be replaced, but at least the correct implementation is preserved by the private <em>download</em> function for other functions that rely on its behavior. This approach is commonly called the <em>“revealing module pattern”</em>.&#160; </ol>
<ol>Another neat approach is to export a constructor function instead of an anonymous object.</ol>
<ol>
<pre class="csharpcode"><span class="kwrd">namespace</span>(<span class="str">'media'</span>);

media.Podcast = (<span class="kwrd">function</span>() {
    <span class="kwrd">var</span> fileExtension = <span class="str">'mp3'</span>;        

    <span class="kwrd">function</span> determineFileExtension() {
        console.log(<span class="str">'File extension is of type '</span> +fileExtension);
    }

    <span class="kwrd">var</span> podcastConstructor = <span class="kwrd">function</span> Podcast(name) {
        <span class="kwrd">if</span>(<span class="kwrd">false</span> === (<span class="kwrd">this</span> instanceof Podcast)) {
            <span class="kwrd">return</span> <span class="kwrd">new</span> Podcast();
        }

        <span class="kwrd">this</span>.getName = <span class="kwrd">function</span>() {
            <span class="kwrd">return</span> name;
        }
    }

    podcastConstructor.prototype.download = <span class="kwrd">function</span> (episode) {
        console.log(<span class="str">'Downloading '</span> + episode + <span class="str">' of '</span> + <span class="kwrd">this</span>.getName());
        determineFileExtension();
    }

    <span class="kwrd">return</span> podcastConstructor;
}());</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</ol>
<ol>Instead of returning an anonymous object from our self-executing function, we create another function and add the <em>download</em> method to the prototype of this constructor function. Notice that we also moved the <em>name</em> parameter to the constructor function instead of passing it into the self-executing function. At the end of the self-executing function we just return this constructor function like we did with the anonymous object. </ol>
<ol>We can now use this module like so … </ol>
<ol>
<pre class="csharpcode"><span class="kwrd">var</span> astronomyCast = <span class="kwrd">new</span> media.Podcast(<span class="str">'Astronomy podcast'</span>);
astronomyCast.download(<span class="str">'the first episode'</span>);</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</ol>
<ol>… which yields the same output as before.</ol>
<ol>The module pattern is a very powerful concept in JavaScript. Being able to expose and use JavaScript code, treating it as a black box, is a very common technique that is used in lots of JavaScript libraries and frameworks. </ol>
<p>Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2011/02/15/basic-javascript-part-10-the-module-pattern/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Taking Baby Steps with Node.js &#8211; Node Version Management with n</title>
		<link>http://elegantcode.com/2011/02/09/taking-baby-steps-with-node-js-node-version-management-with-n/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=taking-baby-steps-with-node-js-node-version-management-with-n</link>
		<comments>http://elegantcode.com/2011/02/09/taking-baby-steps-with-node-js-node-version-management-with-n/#comments</comments>
		<pubDate>Wed, 09 Feb 2011 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Node.js]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2011/02/09/taking-baby-steps-with-node-js-node-version-management-with-n/</guid>
		<description><![CDATA[Here are the links to the previous installments: Introduction Threads vs. Events Using Non-Standard Modules Debugging with node-inspector CommonJS and Creating Custom Modules The community around Node.js is definitely thriving at the moment. As a consequence, new versions of Node.js are being released very rapidly. While the 0.2.x versions of Node.js are considered stable, the [...]]]></description>
			<content:encoded><![CDATA[<p>Here are the links to the previous installments:</p>
<ol>
<li><a href="http://elegantcode.com/2010/11/08/taking-baby-steps-with-node-js-introduction/" target="_blank">Introduction</a></li>
<li><a href="http://elegantcode.com/2010/11/19/taking-baby-steps-with-node-js-threads-vs-events/" target="_blank">Threads vs. Events</a></li>
<li><a href="http://elegantcode.com/2010/12/14/taking-baby-steps-with-node-js-using-non-standard-modules/" target="_blank">Using Non-Standard Modules</a></li>
<li><a href="http://elegantcode.com/2011/01/14/taking-baby-steps-with-node-js-debugging-with-node-inspector/" target="_blank">Debugging with node-inspector</a></li>
<li><a href="http://elegantcode.com/2011/02/04/taking-baby-steps-with-node-js-commonjs-and-creating-custom-modules/" target="_blank">CommonJS and Creating Custom Modules</a></li>
</ol>
<p>The community around <a href="http://nodejs.org/" target="_blank">Node.js</a> is definitely thriving at the moment. As a consequence, new versions of Node.js are being released very rapidly. While the 0.2.x versions of Node.js are considered stable, the 0.3.x versions contain all the new features and latest enhancements. I usually develop against the more stable 0.2.x versions of Node.js while spiking the new stuff in the latest 0.3.x versions in order to get a feel of what’s coming. This means that we need to manage multiple versions of Node.js on our development box while being able to easily switch between the different binaries.</p>
<p>There are a couple of alternative solutions out there that deal with the issue of version management for Node.js. First, there’s <a href="https://github.com/creationix/nvm">nvm</a> which is a simple bash script for managing multiple versions of Node.js. Then there’s also <a href="https://github.com/isaacs/nave">nave</a> which is another shell script that basically does the same thing. But the solution that I’m currently using and going to discuss in this blog post is a tool called <a href="https://github.com/visionmedia/n#readme">n</a>.</p>
<p>We can very easily install <em>n</em> with npm by issuing the following command:</p>
<blockquote><p><em>npm install n</em></p>
</blockquote>
<p>Installing a particular version of node.js is a easy as executing <em>n</em>, specifying the version number: </p>
<blockquote><p><em>n 0.2.6</em></p>
</blockquote>
<p><em>n</em> will get the source code for the requested version and automatically configures/compiles in order to get the binaries. The last version that gets installed this way also automatically becomes the active binary. If we just want to install the latest version of Node.js, we can also use the following command:</p>
<blockquote><p><em>n latest</em></p>
</blockquote>
<p>We can easily check which versions of Node.js that we have installed on our development machine by just executing the following command:</p>
<blockquote><p><em>n</em></p>
</blockquote>
<p>which outputs something like this:</p>
<blockquote><p>&#160;&#160; 0.2.3</p>
<p>o 0.2.6</p>
<p>&#160;&#160; 0.3.7</p>
</blockquote>
<p>You can also check the current version of node.js by executing the following command:</p>
<blockquote><p><font style="background-color: #ffffff"><em>node &#8212; version</em></font></p>
</blockquote>
<p>Running a Node.js application is still done using the same command as before: </p>
<blockquote><p><font style="background-color: #ffffff"><em>node server.js</em></font></p>
</blockquote>
<p>Changing the current active version of Node.js is as simple as executing the same command that we used for installing that particular version:</p>
<blockquote><p><font style="background-color: #ffffff"><em>n 0.2.3</em></font></p>
</blockquote>
<p>This switches the used version of Node.js back to v0.2.3. We can also run an application using a particular version, overriding the current active version: </p>
<blockquote><p><em>n use 0.2.6 server.js</em></p>
</blockquote>
<p>Removing a particular version is pretty easy as well. Just use the following command:</p>
<blockquote><p><em>n rm 0.2.3</em></p>
</blockquote>
<p>That’s it! Being able to quickly switch between the many different versions of Node.js has been a huge time-saver for me so far.&#160; </p>
<p>Until next time.&#160;&#160; </p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2011/02/09/taking-baby-steps-with-node-js-node-version-management-with-n/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Taking Baby Steps with Node.js &#8211; CommonJS and Creating Custom Modules</title>
		<link>http://elegantcode.com/2011/02/04/taking-baby-steps-with-node-js-commonjs-and-creating-custom-modules/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=taking-baby-steps-with-node-js-commonjs-and-creating-custom-modules</link>
		<comments>http://elegantcode.com/2011/02/04/taking-baby-steps-with-node-js-commonjs-and-creating-custom-modules/#comments</comments>
		<pubDate>Sat, 05 Feb 2011 00:19:05 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Node.js]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2011/02/04/taking-baby-steps-with-node-js-commonjs-and-creating-custom-modules/</guid>
		<description><![CDATA[Here are the links to the previous installments: Introduction Threads vs. Events Using Non-Standard Modules Debugging with node-inspector In a previous blog post, I already discussed how to make use of the built-in and third-party modules inside a Node.js application. For this post I’m going to briefly touch on CommonJS and show how to create [...]]]></description>
			<content:encoded><![CDATA[<p>Here are the links to the previous installments:</p>
<ol>
<li><a href="http://elegantcode.com/2010/11/08/taking-baby-steps-with-node-js-introduction/" target="_blank">Introduction</a> </li>
<li><a href="http://elegantcode.com/2010/11/19/taking-baby-steps-with-node-js-threads-vs-events/" target="_blank">Threads vs. Events</a> </li>
<li><a href="http://elegantcode.com/2010/12/14/taking-baby-steps-with-node-js-using-non-standard-modules/" target="_blank">Using Non-Standard Modules</a> </li>
<li><a href="http://elegantcode.com/2011/01/14/taking-baby-steps-with-node-js-debugging-with-node-inspector/" target="_blank">Debugging with node-inspector</a> </li>
</ol>
<p>In a <a href="http://elegantcode.com/2010/12/14/taking-baby-steps-with-node-js-using-non-standard-modules/" target="_blank">previous blog post</a>, I already discussed how to make use of the built-in and third-party modules inside a <a href="http://nodejs.org/" target="_blank">Node.js</a> application. For this post I’m going to briefly touch on <a href="http://www.commonjs.org/" target="_blank">CommonJS</a> and show how to create custom modules. </p>
<p>Most programming languages out there, like Java, Ruby, Python, C#, C++, etc …,&#160; all come with some sort of standard library that provides developers with an API for building all kinds of applications on a variety of platforms. These libraries and/or frameworks provide all kinds of basic functionality for accessing the file system, doing network I/O, parsing command-line arguments, etc. … . Unfortunately, JavaScript doesn’t come with such a standard library. This is something that the <a href="http://www.commonjs.org/" target="_blank">CommonJS</a> initiative is trying to fix. CommonJS tries to go beyond the standard JavaScript specification by defining a common set of API’s for building a broad range of systems like command-line, server-side and GUI applications. If you’re interested, you can have a look at <a href="http://www.commonjs.org/specs/" target="_blank">the current specifications and proposals in development</a>.</p>
<p>What does this have to do with Node.js? Well, Node.js implements the CommonJS specification for its built-in modules. Knowing how to leverage your own custom modules is not only very important for structuring your Node.js applications but also recommended for providing portability with other CommonJS compliant frameworks like <a href="http://narwhaljs.org/" target="_blank">narwhal</a>. Creating a custom module is very easy. We just have to provide a JavaScript file, name it after the module that we want create and add the necessary JavaScript code. That’s it!</p>
<p>Let’s look at a very simple example of how to build such a custom module using the CommonJS system provided by Node.js. Suppose that we want to create a module named <em>podcast</em> that exposes functionality for downloading .mp3 files. As mentioned earlier, we have to create a JavaScript file named <em>podcast.js </em>and add the necessary JavaScript code that provides the download functionality.</p>
<pre class="csharpcode">exports.download = <span class="kwrd">function</span>(episode) {
    console.log(<span class="str">'Downloading: '</span> + episode);
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>A slight variation to this that I see quite often used both in the built-in as the third-party modules looks like the following:</p>
<pre class="csharpcode"><span class="kwrd">var</span> podcast = exports;

podcast.download = <span class="kwrd">function</span>(episode) {
    console.log(<span class="str">'Downloading: '</span> + episode);
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>In order to use this exciting new piece of code, we just have to add a <em>require</em> statement to our client code and we’re good to go:</p>
<pre class="csharpcode"><span class="kwrd">var</span> podcast = require(<span class="str">&quot;./podcast&quot;</span>);
podcast.download(<span class="str">'Astronomy podcast #89'</span>);</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This might look very simple and easy but there’s plenty going on behind the scenes. First of all, Node.js ensures that the content of the JavaScript file that makes up our custom module gets loaded into its own scope. By doing this, Node.js automatically prevents naming collisions with other modules. When loading our custom module, Node.js provides a number of objects like <em>module</em>, <em>exports</em> and <em>require</em>. These are also called pseudo globals.</p>
<p>We use the <em>exports</em> object for exposing public members to external code. You can consider <em>exports</em> as the <em>this</em> reference for our module. This also means that we can just add regular JavaScript functions to our custom module without adding them to the global namespace and without the external code being able to call these<em> ‘private’</em> functions as long as we don’t add them to the <em>exports</em> object.</p>
<pre class="csharpcode"><span class="kwrd">var</span> podcast = exports;

podcast.download = <span class="kwrd">function</span>(episode) {
    downloadDataFor(episode);
}

<span class="kwrd">function</span> downloadDataFor(episode) {
    console.log(<span class="str">'Downloading: '</span> + episode);
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>The external code is not able to call the <em>downloadDataFor</em> function which is only available inside our custom module:</p>
<pre class="csharpcode"><span class="kwrd">var</span> podcast = require(<span class="str">&quot;./podcast&quot;</span>);
podcast.download(<span class="str">'Astronomy podcast #89'</span>);

console.log(<span class="kwrd">typeof</span> podcast.download);            <span class="rem">// function</span>
console.log(<span class="kwrd">typeof</span> podcast.downloadDataFor);    <span class="rem">// undefined</span>
console.log(<span class="kwrd">typeof</span> downloadDataFor);            // undefined</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>I just mentioned that a module is provided with a couple of pseudo global objects. One of these is named <em>module </em>which provides a reference to the current instance of the module. This means that we are able to replace the reference that is hold by the <em>exports</em> property of the current module in order to provide a single export per JavaScript file. Let’s talk code:&#160; </p>
<pre class="csharpcode">function Podcast() {
    <span class="kwrd">if</span>(<span class="kwrd">false</span> === (<span class="kwrd">this</span> instanceof Podcast)) {
        <span class="kwrd">return</span> <span class="kwrd">new</span> Podcast();
    }
}

Podcast.prototype.download = function(episode) {
    console.log(<span class="str">'Downloading: '</span> + episode);
}

module.exports = Podcast;</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>We now have to use restructure the client code as well:</p>
<pre class="csharpcode"><span class="kwrd">var</span> Podcast = require(<span class="str">&quot;./podcast&quot;</span>);

<span class="kwrd">var</span> astronomyCast = <span class="kwrd">new</span> Podcast();
astronomyCast.download(<span class="str">'Astronomy podcast #89'</span>);</pre>
<p>The advantage of this approach is that both the code of our custom module as well as the client code are organized in the same way as we would write regular JavaScript objects.&#160; </p>
<p>I can only hope that the CommonJS initiative succeeds in its goals by providing a common set of API’s that can be used for building a wide range of applications using JavaScript. Using modules interchangeably on all kinds of platforms still sounds very appealing <img src='http://elegantcode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> . </p>
<p>Until next time. </p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2011/02/04/taking-baby-steps-with-node-js-commonjs-and-creating-custom-modules/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Basic JavaScript Part 9: Reusing Methods of Other Objects</title>
		<link>http://elegantcode.com/2011/01/31/basic-javascript-part-9-reusing-methods-of-other-objects/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=basic-javascript-part-9-reusing-methods-of-other-objects</link>
		<comments>http://elegantcode.com/2011/01/31/basic-javascript-part-9-reusing-methods-of-other-objects/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2011/01/31/basic-javascript-part-9-reusing-methods-of-other-objects/</guid>
		<description><![CDATA[Here are the links to the previous installments: Functions Objects Prototypes Enforcing New on Constructor Functions Hoisting Automatic Semicolon Insertion Static Properties and Methods Namespaces In one of my previous posts, I mentioned that functions in JavaScript are plain objects that can have their own properties and methods. One of these methods that are available [...]]]></description>
			<content:encoded><![CDATA[<p>Here are the links to the previous installments:</p>
<ol>
<li><a href="http://elegantcode.com/2010/10/22/basic-javascript-part-1-functions/" target="_blank">Functions</a></li>
<li><a href="http://elegantcode.com/2010/11/12/basic-javascript-part-2-objects/" target="_blank">Objects</a></li>
<li><a href="http://elegantcode.com/2010/12/03/basic-javascript-part-3-prototypes/" target="_blank">Prototypes</a></li>
<li><a href="http://elegantcode.com/?p=4015" target="_blank">Enforcing New on Constructor Functions</a></li>
<li><a href="http://elegantcode.com/2010/12/24/basic-javascript-part-5-hoisting/" target="_blank">Hoisting</a></li>
<li><a href="http://elegantcode.com/2011/01/12/basic-javascript-part-6-automatic-semicolon-insertion/" target="_blank">Automatic Semicolon Insertion</a></li>
<li><a href="http://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/" target="_blank">Static Properties and Methods</a></li>
<li><a href="http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/" target="_blank">Namespaces</a></li>
<p> In <a href="http://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/" target="_blank">one of my previous posts</a>, I mentioned that functions in JavaScript are plain objects that can have their own properties and methods. One of these methods that are available for every function object is a method named <em>call(), </em>which is defined on the prototype of <em>Function. </em>This method allows you to <em>‘reuse’</em> a method from another object. Let’s talk code.Suppose we have an object called <em>podcast</em> which has a <em>download()</em> function:
<pre class="csharpcode"><span class="kwrd">var</span> podcast = {
    name : <span class="str">'Astronomy podcast'</span>,
    download : <span class="kwrd">function</span>(episode) {
        console.log(<span class="str">'Downloading '</span> + episode + <span class="str">' of '</span> + <span class="kwrd">this</span>.name);
    }
};

podcast.download(<span class="str">'the first episode'</span>);</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>The output we get by executing this function is exactly what we expect it to be:</p>
<blockquote style="margin-right: 0px" dir="ltr">
<p><em>“Downloading the first episode of Astronomy podcast”</em></p>
</blockquote>
<p>Now suppose we bring on another object called <em>screencast</em> :</p>
<pre class="csharpcode"><span class="kwrd">var</span> screencast = {
    name: <span class="str">'Node tuts'</span>
};</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Wouldn’t it be nice if we could somehow reuse the <em>download()</em> method of the <em>podcast</em> object so that we can download a <em>screencast</em> as well. We can do this by invoking <em>call()</em> on the <em>download()</em> method like so:&#160;
<pre class="csharpcode">podcast.download.call(screencast, <span class="str">'the last episode'</span>);</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This gives us the following output:</p>
<blockquote style="margin-right: 0px" dir="ltr">
<p><em>“Downloading the last episode of Node tuts”</em></p>
</blockquote>
<p>What exactly happened here? Well, we just invoked the <em>call()</em> method on the <em>download</em> function object, specifying a reference to the <em>screencast</em> object and a string argument that describes the particular episode. The <em>download()</em> method got invoked with the <em>screencast</em> object bound to <em>this</em>. Therefore, the <em>download()</em> method uses the <em>name</em> property of the <em>screencast</em> object instead of the <em>name</em> of the <em>podcast</em> object.</ol>
<ol>There’s also another method with similar functionality defined on the Function prototype named <em>apply()</em>. This method behaves exactly the same as the <em>call()</em> method, except that the arguments passed to the underlying method in question need to be passed as an array.</p>
<pre class="csharpcode">podcast.download.apply(screencast, [<span class="str">'the last episode'</span>]);</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Utilizing the <em>call()/apply()</em> methods is a very powerful way to reuse features of objects that are built into JavaScript (like Array, String, etc. …) or from third-party libraries. But I don’t recommend applying this technique when you own the code of the method you want to reuse. A simple refactoring like extracting the particular method into another object is a much better approach.</ol>
<p>Until next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2011/01/31/basic-javascript-part-9-reusing-methods-of-other-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Basic JavaScript Part 8: Namespaces</title>
		<link>http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=basic-javascript-part-8-namespaces</link>
		<comments>http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/#comments</comments>
		<pubDate>Wed, 26 Jan 2011 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/</guid>
		<description><![CDATA[Here are the links to the previous installments: Functions Objects Prototypes Enforcing New on Constructor Functions Hoisting Automatic Semicolon Insertion Static Properties and Methods In my previous post, I showed how you can ‘emulate’ static members in JavaScript without having a dedicated syntax for it. For this post, I’m going to discuss namespaces in JavaScript. [...]]]></description>
			<content:encoded><![CDATA[<p>Here are the links to the previous installments:</p>
<ol>
<li><a href="http://elegantcode.com/2010/10/22/basic-javascript-part-1-functions/">Functions</a> </li>
<li><a href="http://elegantcode.com/2010/11/12/basic-javascript-part-2-objects/">Objects</a> </li>
<li><a href="http://elegantcode.com/2010/12/03/basic-javascript-part-3-prototypes/">Prototypes</a> </li>
<li><a href="http://elegantcode.com/?p=4015">Enforcing New on Constructor Functions</a> </li>
<li><a href="http://elegantcode.com/2010/12/24/basic-javascript-part-5-hoisting/">Hoisting</a> </li>
<li><a href="http://elegantcode.com/2011/01/12/basic-javascript-part-6-automatic-semicolon-insertion/">Automatic Semicolon Insertion</a> </li>
<li><a href="http://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/">Static Properties and Methods</a> </li>
</ol>
<p>In my <a href="http://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/">previous post</a>, I showed how you can <em>‘emulate’</em> static members in JavaScript without having a dedicated syntax for it. For this post, I’m going to discuss namespaces in JavaScript. In order to reduce the number of objects and functions that are added to the global scope in our applications, using namespaces in JavaScript is definitely a recommended practice. Just like static members, namespaces don’t have any dedicated syntax built into the language either. But we’re able to get the same benefits by creating a single global object and adding all our objects and functions to this object.</p>
<pre class="csharpcode"><span class="kwrd">var</span> AppSpace = AppSpace || {};

AppSpace.Podcast = <span class="kwrd">function</span> {
    <span class="kwrd">this</span>.title = <span class="str">'Astronomy Cast'</span>;
    <span class="kwrd">this</span>.description = <span class="str">'A fact-based journey through the galaxy.'</span>;
    <span class="kwrd">this</span>.link = <span class="str">'http://www.astronomycast.com'</span>;
};

AppSpace.Podcast.prototype.toString = <span class="kwrd">function</span>() {
    <span class="kwrd">return</span> <span class="str">'Title: '</span> + <span class="kwrd">this</span>.title;
}</pre>
<p>This way we lower the possibility of naming collisions when using our code in conjunction with other JavaScript libraries. We can also use the same naming conventions for namespaces as in any other programming language that does provide syntactical support. Suppose we want to use a namespace like “<em>MyCompany.MyApplication.Model”</em>. We can accomplish this by using the same approach as shown earlier:</p>
<pre class="csharpcode"><span class="kwrd">var</span> MyCompany = MyCompany || {};
MyCompany.MyApplication = {};
MyCompany.MyApplication.Model = {};</pre>
<p>or something like the following:</p>
<pre class="csharpcode"><span class="kwrd">var</span> MyCompany = MyCompany || {
    MyApplication: {
        Model: {}
    }
};</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>However, this approach can become very cumbersome and hard to maintain when our code expands over time. In order to overcome this issue we can use a general purpose namespace function to achieve the same thing using a single line of code.</p>
<pre class="csharpcode"><span class="kwrd">var</span> model = <span class="kwrd">namespace</span>(<span class="str">'MyCompany.MyApplication.Model'</span>);

model.Podcast = <span class="kwrd">function</span> {
    <span class="kwrd">this</span>.title = <span class="str">'Astronomy Cast'</span>;
    <span class="kwrd">this</span>.description = <span class="str">'A fact-based journey through the galaxy.'</span>;
    <span class="kwrd">this</span>.link = <span class="str">'http://www.astronomycast.com'</span>;
};

model.Podcast.prototype.toString = <span class="kwrd">function</span>() {
    <span class="kwrd">return</span> <span class="str">'Title: '</span> + <span class="kwrd">this</span>.title;
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Here’s an example of how we can implement such a namespace function.</p>
<pre class="csharpcode"><span class="kwrd">function</span> <span class="kwrd">namespace</span>(namespaceString) {
    <span class="kwrd">var</span> parts = namespaceString.split(<span class="str">'.'</span>),
        parent = window,
        currentPart = <span class="str">''</span>;    

    <span class="kwrd">for</span>(<span class="kwrd">var</span> i = 0, length = parts.length; i &lt; length; i++) {
        currentPart = parts[i];
        parent[currentPart] = parent[currentPart] || {};
        parent = parent[currentPart];
    }

    <span class="kwrd">return</span> parent;
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Using this approach requires less typing and the resulting code also looks less verbose. Some JavaScript libraries, like YUI and the Dojo Toolkit, provide their own implementations for such a namespace utility function. I encourage you to take a look at their implementations as well.</p>
<p>Until next time.&#160; </p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Basic JavaScript Part 7: Static Properties and Methods</title>
		<link>http://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=basic-javascript-part-7-static-properties-and-methods</link>
		<comments>http://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/#comments</comments>
		<pubDate>Wed, 19 Jan 2011 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/</guid>
		<description><![CDATA[Here are the links to the previous installments: Functions Objects Prototypes Enforcing New on Constructor Functions Hoisting Automatic Semicolon Insertion In this post, I’m going to quickly show you how to set up static properties and methods in JavaScript. This can come in handy for constant values and/or utility functions. C# and most other class-based [...]]]></description>
			<content:encoded><![CDATA[<p>Here are the links to the previous installments:</p>
<ol>
<li><a href="http://elegantcode.com/2010/10/22/basic-javascript-part-1-functions/">Functions</a></li>
<li><a href="http://elegantcode.com/2010/11/12/basic-javascript-part-2-objects/">Objects</a></li>
<li><a href="http://elegantcode.com/2010/12/03/basic-javascript-part-3-prototypes/">Prototypes</a></li>
<li><a href="http://elegantcode.com/?p=4015">Enforcing New on Constructor Functions</a></li>
<li><a href="http://elegantcode.com/2010/12/24/basic-javascript-part-5-hoisting/">Hoisting</a></li>
<li><a href="http://elegantcode.com/2011/01/12/basic-javascript-part-6-automatic-semicolon-insertion/">Automatic Semicolon Insertion</a></li>
</ol>
<ol>In this post, I’m going to quickly show you how to set up static properties and methods in JavaScript. This can come in handy for constant values and/or utility functions. C# and most other class-based languages have a special syntax for static members. Not so for JavaScript. Although JavaScript doesn’t provide a dedicated syntax for static members, we’re still able to get what we want by adding properties and methods to a constructor function. This is possible because functions in JavaScript are plain objects that can have properties and methods of their own.&#160; </ol>
<ol>Let’s show some code. </ol>
<ol>
<pre class="csharpcode"><span class="kwrd">function</span> Podcast() {};

Podcast.FILE_EXTENSION = <span class="str">'mp3'</span>;
Podcast.download = <span class="kwrd">function</span>(podcast) {
    console.log(<span class="str">'Downloading '</span> + podcast + <span class="str">' ...'</span>);
};

Podcast.prototype.play = <span class="kwrd">function</span>() {
    console.log(<span class="str">'Playing this podcast ...'</span>);
};</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</ol>
<p>Here we created a constructor function named <em>Podcast</em> with a static property called <em>FILE_EXTENSION</em> and a static method named <em>download</em>. We also added the instance method <em>play()</em> to the prototype of our constructor function.</p>
<p>Getting the value of a static property or invoking a static method is done as follows:</p>
<pre class="csharpcode">Podcast.FILE_EXTENSION;                <span class="rem">// 'mp3'</span>
Podcast.download(<span class="str">'Astronomy cast'</span>);    // <span class="str">'Downloading Astronomy cast ...'</span></pre>
<p>When we create a <em>Podcast</em> object and invoke the instance method <em>play()</em>, we obviously get the expected outcome. </p>
<pre class="csharpcode"><span class="kwrd">new</span> Podcast().play();    // <span class="str">'Playing this podcast ...'</span></pre>
<p>But it’s surely not possible to statically invoke an instance method like so: </p>
<pre class="csharpcode">Podcast.play();        // undefined</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>It’s also not possible to invoke a static method on a <em>Podcast</em> instance object either.</p>
<pre class="csharpcode"><span class="kwrd">new</span> Podcast().download(<span class="str">'Railscasts'</span>);    // undefined</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>There you go. Knowing how to provide static members in JavaScript might come in handy when you feel inspired of writing your own Math class in JavaScript <img src='http://elegantcode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
<p>Until next time. </p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Taking Baby Steps with Node.js &#8211; Debugging with node-inspector</title>
		<link>http://elegantcode.com/2011/01/14/taking-baby-steps-with-node-js-debugging-with-node-inspector/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=taking-baby-steps-with-node-js-debugging-with-node-inspector</link>
		<comments>http://elegantcode.com/2011/01/14/taking-baby-steps-with-node-js-debugging-with-node-inspector/#comments</comments>
		<pubDate>Fri, 14 Jan 2011 22:42:42 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Node.js]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2011/01/14/taking-baby-steps-with-node-js-debugging-with-node-inspector/</guid>
		<description><![CDATA[Here are the links to the previous installments: Introduction Threads vs. Events Using Non-Standard Modules Writing unit tests for your code drastically reduces the amount of debugging. This is the case for practically any programming language that you work in. But when the shit hits the fan, having a debugger with some decent features at [...]]]></description>
			<content:encoded><![CDATA[<p>Here are the links to the previous installments:</p>
<ol>
<li><a href="http://elegantcode.com/2010/11/08/taking-baby-steps-with-node-js-introduction/">Introduction</a></li>
<li><a href="http://elegantcode.com/2010/11/19/taking-baby-steps-with-node-js-threads-vs-events/">Threads vs. Events</a></li>
<li><a href="http://elegantcode.com/2010/12/14/taking-baby-steps-with-node-js-using-non-standard-modules/">Using Non-Standard Modules</a></li>
</ol>
<p>Writing unit tests for your code drastically reduces the amount of debugging. This is the case for practically any programming language that you work in. But when the shit hits the fan, having a debugger with some decent features at your disposal is a must. However Node.js doesn’t come with a debugger out of the box. Thankfully there are a couple of debuggers out there like <a href="https://github.com/smtlaissezfaire/ndb">ndb</a>, <a href="https://github.com/marak/node_debug">node-debug</a> and <a href="https://github.com/dannycoates/node-inspector">node-inspector</a>, which I’ll going to be demonstrating in this blog post. For this blog I’m going to show you some of the nice capabilities of node-inspector.</p>
<p>Installing node-inspector is actually pretty easy when you have <a href="http://elegantcode.com/2010/11/08/taking-baby-steps-with-node-js-introduction/">npm installed</a>. Just issue the following command:</p>
<blockquote><pre><code>npm install node-inspector</code></pre>
</blockquote>
<p>Now we can startup node-inspector … </p>
<blockquote>
<pre><code>node-inspector &amp;</code></pre>
</blockquote>
<p>which shows the following output if all goes well:</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2011/01/image2.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="image" border="0" alt="image" align="left" src="http://elegantcode.com/wp-content/uploads/2011/01/image_thumb2.png" width="480" height="144" /></a> </p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>Now that we have node-inspector running, we can start debugging our node.js application in another console:</p>
<blockquote>
<pre><code>node --debug server.js</code></pre>
</blockquote>
<p>which outputs the port on which the debugger is listening.</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2011/01/image3.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="image" border="0" alt="image" align="left" src="http://elegantcode.com/wp-content/uploads/2011/01/image_thumb3.png" width="470" height="96" /></a> </p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>Now you can open <a href="http://www.google.com/chrome">Chrome</a> and point it to the following URL:</p>
<blockquote>
<p><a title="http://127.0.0.1:8080/" href="http://127.0.0.1:8080/">http://127.0.0.1:8080/</a></p>
</blockquote>
<p>If all goes well, then we’ll get to see some JavaScript source code:</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2011/01/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="image" border="0" alt="image" align="left" src="http://elegantcode.com/wp-content/uploads/2011/01/image_thumb4.png" width="591" height="384" /></a> </p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>Note that you’ll have to use Chrome or another WebKit based browser for opening node-inspector. I also tried it in Firefox, but the page doesn’t show at all. </p>
<p>You can then select the JavaScript source file that contains the code you wish to debug and add breakpoints like you would normally do in an IDE like Visual Studio. </p>
<p>Now we can start using our application until we hit a breakpoint.</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2011/01/image5.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="image" border="0" alt="image" align="left" src="http://elegantcode.com/wp-content/uploads/2011/01/image_thumb5.png" width="587" height="388" /></a> </p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>On the right of the page we can add watch expressions, look at the call stack and the current values of the scope variables. In the code window we have the usual suspects like “Step over”, “Step into next function” and “Step out of current function”. We can even do live editing and all of this right in the browser! Tooltips also work as expected.</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2011/01/image6.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="image" border="0" alt="image" align="left" src="http://elegantcode.com/wp-content/uploads/2011/01/image_thumb6.png" width="578" height="383" /></a> </p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<p>Another nice feature is the console window that can be shown/hidden below or taking over the entire window by clicking the menu button at the top of the page. </p>
<p><a href="http://elegantcode.com/wp-content/uploads/2011/01/image7.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2011/01/image_thumb7.png" width="574" height="380" /></a> </p>
<p>Because I’ve been using version 0.2.3 for developing my very first application using Node.js, I had to install an older version of node-inspector. If you decide to use the latest version of Node.js, you will see that a couple of interesting new features have been added, like heap snapshots. Make sure to watch <a href="http://www.youtube.com/watch?v=AOnK3NVnxL8">this short screen cast</a> to get up and running in no time with node-inspector. </p>
<p>Using node-inspector while developing Node.js applications can really save you a lot of grief. It certainly helped me to find a couple of bugs that would otherwise be hard to track down. It’s also a great learning tool if you would like to learn more about how Node.js behaves at runtime.</p>
<p>Until next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2011/01/14/taking-baby-steps-with-node-js-debugging-with-node-inspector/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

