<?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>emson... &#187; javascript</title>
	<atom:link href="http://blog.emson.co.uk/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.emson.co.uk</link>
	<description></description>
	<lastBuildDate>Thu, 24 Jun 2010 08:27:48 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>JavaScript The Good Parts Best Practices</title>
		<link>http://blog.emson.co.uk/2010/04/javascript-the-good-parts-best-practices/</link>
		<comments>http://blog.emson.co.uk/2010/04/javascript-the-good-parts-best-practices/#comments</comments>
		<pubDate>Fri, 09 Apr 2010 18:05:47 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[bestpractice]]></category>
		<category><![CDATA[books]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://blog.emson.co.uk/?p=88</guid>
		<description><![CDATA[Part I

The best practice suggestions listed here are summaries from Douglas Crockford&#8217;s book: JavaScript: The Good Parts

By following these principles you will write better JavaScript code.

JavaScript Best Practices

1. Commenting

Avoid using /* */ for commenting out your code instead use the // method.  The reason being that */ can occur in regular expressions and if [...]]]></description>
			<content:encoded><![CDATA[<h2>Part I</h2>

<p>The best practice suggestions listed here are summaries from <a href="http://www.crockford.com/">Douglas Crockford&#8217;s</a> book: <a href="http://www.amazon.com/gp/product/0596517742?ie=UTF8&amp;tag=emson-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0596517742">JavaScript: The Good Parts</a></p>

<p>By following these principles you will write better JavaScript code.</p>

<h2>JavaScript Best Practices</h2>

<h3>1. Commenting</h3>

<p>Avoid using <code>/* */</code> for commenting out your code instead use the <code>//</code> method.  The reason being that <code>*/</code> can occur in regular expressions and if you were to comment out a regular expression containing this, you would get a syntax error.</p>

<h3>2. Object Value Retrieval</h3>

<p>For an object such as <code>var myObj = {key:"value"};</code> An object value can retrieved in two ways:</p>

<ol>
<li>myObj["key"]; // &#8220;value&#8221;</li>
<li>myObj.key; // &#8220;value&#8221;</li>
</ol>

<p>However the second version using &#8216;.&#8217; notation is preferred as it reads better.</p>

<h3>3. Avoid Global Variables</h3>

<p>Global variables will reduce the resiliency of your JavaScript programs so try to keep these to a minimum.  A best practice strategy for this is to use a single global variable for your program and simply assign objects to it. e.g.</p>

<pre><code>var MYAPP = {};

MYAPP.myObj = {
  key:"value"
};
</code></pre>

<h3>4. Capitalize Constructor Functions</h3>

<p>Functions that are created as <em>constructor functions</em> should be capitalized. Think of a <em>constructor functions</em> as a factory creating cloned functions.  Strictly this is not classical inheritance but <strong>prototypical inheritance</strong>. This is essentially where a function is cloned and contains all the properties of it&#8217;s parent.</p>

<pre><code>var Shape = function (name) {
  this.name = name;
};

var square = new Shape("square");
</code></pre>

<p>This style of constructor functions is not recommended as if you forget to use <code>new</code> then the <code>this</code> object gets bound to the global variable.</p>

<h3>5. Avoid Recursion</h3>

<p>JavaScript does not offer <em>tail recursion optimization</em>, therefore functions that recurse too deeply will eventually fail.</p>

<h3>6. Use Function Scope To Protect Against Namespace Collisions</h3>

<p>JavaScript does not have block scope, i.e. variables declared in a block statement (e.g. with in curly braces) are accessible from outside of that block.  However functions do have function scope, variables declared within a function cannot be accessed from outside of that function.</p>

<p>Best practice is to declare the variables used in a function at the top of the function.</p>

<h3>7. Use Functions To Create Modules</h3>

<p>A Module is a function or object that presents an interface but hides its state and implementation. This therefore avoids the use of global variables.</p>

<pre><code>var myModule = function() {
  var call = '';

  return {
    setCall: function(myCall) {
      call = String(myCall);
    },
    doCall: function() {
      return 'Hello ' + call;
    }
  };
}();  // the () will immediately invoke this function

var myCaller = myModule();
myCaller.setCall = 'Ben';
alert( myCaller.doCall() );
</code></pre>

<h3>8. Use Cascades</h3>

<p>If you have a method that changes state, be sure to return <code>this</code> as opposed to <code>undefined</code>. The reason is that you can then chain these methods together.  This is how JQuery works.</p>

<pre><code>getElement('myDiv').changeColour('red').setFont('Times').setStyle('italic');
</code></pre>

<h3>9. For Constructor That Take Many Parameters Use Object Specifiers</h3>

<p>If an object takes many parameters it can be tricky ensuring that these parameters are in the correct order. Therefore create a single object instead that holds all the parameters as properties:</p>

<pre><code>// Tricky
var myObj = someObject(a, b, c, d);

// Better
var myObj = someObject({ first: a, second: b, third: c, fourth: d});
</code></pre>

<h2>General JavaScript Notes</h2>

<p>Strings are immutable, in that once a string has been created that string object cannot be changed. However note that you can easily append and modify a string, the outcome just generates a new string.</p>

<p>JavaScript provides a prototype linkage function, which when used allows one object to &#8216;inherit&#8217; the properties of the linked object.</p>

<p>A <code>try catch</code> statement only allows a single catch block, to catch all exceptions. If you need to differentiate between exceptions then add code to inspect the name of the exception and handle it appropriately.</p>

<h3>Objects</h3>

<p>Object creation methods:</p>

<ol>
<li><code>var myObj = {};</code></li>
</ol>

<p>Set a default value if an object property doesn&#8217;t exist:</p>

<pre><code>var myObj = {one:"1"};
myObj.two || "2" // returns "2"
</code></pre>

<p>Assigning a value to an object property that is undefined will simply augment (or create) that property in that object and assign it.</p>

<p>Objects are passed by reference, they are never copied.</p>

<p>Every object is linked to a prototype object from which it can inherit properties. This object is <code>Object.prototype</code></p>

<p>The prototype link is only used in the retrieval of properties from objects, if the first object does not have the property then JavaScript will use this prototype link to get the next object up the chain and try and retrieve the property from this object. If no property exists then <code>undefined</code> is returned.</p>

<p>When using <code>for in</code> for enumerating over properties in an object, be aware that it will also enumerate the properties of objects further up the prototype chain.  If you don&#8217;t want this simply just use <code>for</code>,</p>

<h3>Functions</h3>

<p>As Douglas Crockford says:</p>

<blockquote>
  <p>Functions are the fundamental modular unit of JavaScript. Use functions for code reuse, information hiding and composition. Functions are used to specify the behaviour of objects.</p>
</blockquote>

<p>Functions are objects, but they have a prototype link to <code>Function.prototype</code>, and then this root function object in turn links to <code>Object.prototype</code>.</p>

<p>A function can take 0 or more specified parameters, however functions get two extra hidden parameters <code>this</code> and <code>arguments</code>.</p>

<p>A <strong>method</strong> is simply a function assigned (bound) to an objects property. e.g.</p>

<pre><code>var myObj = {
  myMethod: function (name) {
    alert("Hello " + name);
  };
};
</code></pre>

<p>A function always returns a value. If no return value is defined then the function will return <code>undefined</code>. However if a function is constructed with the <code>new</code> prefix and the return value is not an object the new object is returned.</p>

<h2>JavaScript Gotcha&#8217;s</h2>

<h3>typeof Returns incorrect types</h3>

<p>Using the <code>typeof</code> method will return six results:</p>

<ol>
<li>number</li>
<li>string</li>
<li>boolean</li>
<li>undefined</li>
<li>function</li>
<li>object</li>
</ol>

<p>The problem occurs with <code>typeof ['1']</code> or <code>typeof null</code> which both return <em>object</em> which is incorrect.</p>

<h3>Function Invocation Binds &#8216;this&#8217; To The Global Object</h3>

<p>When a function is created by assigning it to a global variable, and the contents of that function contains a <code>this</code> statement then the <code>this</code> is bound to the Global Object</p>

<p>When a function, contains an internal function the <code>this</code> of the internal function is bound to the Global Object and not the <code>this</code> of the parent function. To fix this simply assign <code>this</code> to a <code>that</code> variable and use <code>that</code> within your internal function.</p>

<pre><code>var myObj = {
  value: 0;

  double: function() {
    var that = this;
    var helper = function() {
      that.value = that.value + that.value;
    };
    helper();
  };
};
</code></pre>

<h3>arguments Is An Array Like Object Not An Array</h3>

<p>All functions have a parameter <code>arguments</code> which gives a function access to all the arguments supplied with it&#8217;s invocation &#8211; including excess arguments that are not assigned to a parameter.
However note that <code>arguments</code> is in fact a special object with a length method and not an Array object. So <code>arguments</code> will lack methods that an Array object will have.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.emson.co.uk/2010/04/javascript-the-good-parts-best-practices/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>SproutCore and Web Applications</title>
		<link>http://blog.emson.co.uk/2008/08/sproutcore-and-web-applications/</link>
		<comments>http://blog.emson.co.uk/2008/08/sproutcore-and-web-applications/#comments</comments>
		<pubDate>Mon, 18 Aug 2008 10:00:56 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[business]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[sproutcore javascript ruby]]></category>

		<guid isPermaLink="false">http://blog.emson.co.uk/?p=15</guid>
		<description><![CDATA[It&#8217;s been a wee while since my last article, which has largely been due to my summer holiday.
Anyway I&#8217;ve been reading up and experimenting with the SproutCore JavaScript framework.

Its excellent but I wanted to explain why companies and developers should consider using it.  So I&#8217;ve written an article on my business partner&#8217;s web site [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a wee while since my last article, which has largely been due to my summer holiday.
Anyway I&#8217;ve been reading up and experimenting with the <a href="http://www.sproutcore.com">SproutCore</a> JavaScript framework.</p>

<p>Its excellent but I wanted to explain why companies and developers should consider using it.  So I&#8217;ve written an article on my business partner&#8217;s web site <a href="http://rapidappsgroup.com/content/desktop-web-applications-using-sproutcore/">http://rapidappsgroup.com/content/desktop-web-applications-using-sproutcore/</a>. <br/></p>

<p>Please check it out as it tries to answer a lot of the general questions about web applications and JavaScript frameworks.</p>

<p>BE&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.emson.co.uk/2008/08/sproutcore-and-web-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
