<?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>code zen &#187; JavaScript</title>
	<atom:link href="http://www.arpitonline.com/blog/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.arpitonline.com/blog</link>
	<description>"I write pretty software"</description>
	<lastBuildDate>Sun, 25 Jul 2010 22:23:39 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Object Oriented JavaScript Techniques</title>
		<link>http://www.arpitonline.com/blog/2009/07/24/object-oriented-javascript-techniques/</link>
		<comments>http://www.arpitonline.com/blog/2009/07/24/object-oriented-javascript-techniques/#comments</comments>
		<pubDate>Fri, 24 Jul 2009 20:06:29 +0000</pubDate>
		<dc:creator>arpit</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.arpitonline.com/blog/?p=276</guid>
		<description><![CDATA[This post is in response to a couple of conversations I had with some friends around OOP in JavaScript. Over the last couple of months I have gotten really deep into the language with JQuery (which is a fantastic library by the way) so I thought I&#8217;d quickly list some techniques I have been using [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 20px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.arpitonline.com%2Fblog%2F2009%2F07%2F24%2Fobject-oriented-javascript-techniques%2F"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.arpitonline.com%2Fblog%2F2009%2F07%2F24%2Fobject-oriented-javascript-techniques%2F" height="61" width="51" /></a></div><p>This post is in response to a couple of conversations I had with some friends around OOP in JavaScript. Over the last couple of months I have gotten really deep into the language with JQuery (which is a fantastic library by the way) so I thought I&#8217;d quickly list some techniques I have been using to structure my JavaScript code.</p>
<p><u><strong>Creating a very simple class with an instance variable:</strong></u><br />
JavaScript has no concept of classes but they can be mimic-ed by creative uses of the Function object. So for example this is completely valid:</p>
<p><code></p>
<pre>
var vanillaFunction = function(){
	this.name = "vanilla"
}
var instance = new vanillaFunction();
alert(instance.name) //	vanilla
</pre>
<p></code><br />
In the above case, &#8220;name&#8221; becomes an instance variable of the vanillaFunction class. </p>
<p><u><strong>Constructing instance methods</strong></u><br />
<code></p>
<pre>
var vanillaFunction = function(){
	this.name = "vanilla";
	this.sampleMethod = function(){
		return "SampleMethod was called";
	}
}

var instance = new vanillaFunction();
alert(instance.sampleMethod())
</pre>
<p></code></p>
<p>Under the hood whats going on is that the JavaScript interpreter is attaching the Function objects to the vanillaFunction&#8217;s prototype chain. So to add another function, we can append that function right on the prototype:</p>
<p><code></p>
<pre>
vanillaFunction.prototype.getName() = function(){
	return this.name; // returns "vanilla"
}
</pre>
<p></code></p>
<p>Note that these functions have access to the name instance variable defined in the main vanillaFunction class.</p>
<p><u><strong>Creating class variables and methods (kinda):</strong></u><br />
Since all functions are essentially Objects, variables can be tagged on to the function object and then referenced as static class variables.</p>
<p><code><br />
vanillaFunction.classVar = "some value here";<br />
</code></p>
<p>Same way, static functions can be created as well:</p>
<p><code></p>
<pre>
vanillaFunction.staticFunction = function(){
	alert("static function called");
}
</pre>
<p></code></p>
<p>However it should be noted that the static variables and methods do not have access to each other unless explicitly passed during invocation. Personally, I hardly ever use this and prefer static classes as shown below.</p>
<p><u><strong>Creating Static classes:</strong></u><br />
A static class is one you can never create a new instance of. For example, instead of having static methods in a JavaScript class, you can create a static class by declaring your functions as variables on a pure JavaScript Object. This method can be used for example for creating a class of utility functions:</p>
<p><code></p>
<pre>
var utils = {
	trim:function(str, numCharacters){
		return str.substring(0, numCharacters);
	},

	log:function(msg){
		if(console){
			console.log(msg);
		}
	}
}
var s = utils.trim("Good day to you sir", 4);
</pre>
<p></code></p>
<p><u><strong>Creating classes with JQuery</strong></u><br />
To create a class with JQuery, we use the jQuery.extend function which pretty much adds the instance methods to the prototype chain as we saw before:</p>
<p><code><br />
MyClass = function(){<br />
	this.title = "MyClass";<br />
};</p>
<p>$j.extend(MyClass.prototype, {<br />
	toString:function(){<br />
		return this.title;<br />
	}<br />
});<br />
</code></p>
<p><u><strong>Events:</strong></u><br />
Even though the ECMAScript specification defines events and how they work, they are not implemented consistently across browsers. The JQuery event system is much nicer since a) it works cross-browser and b) the event source doesn&#8217;t necessarily have to be a DOM element. </p>
<p><code><br />
var obj = {name:"SimpleObj"};<br />
jQuery(obj).bind("objectChanged", listener);<br />
jQuery(obj).bind("objectChanged", listener);<br />
jQuery(obj).trigger({type:"objectChanged"});<br />
</code></p>
<p>In the above example, we are binding to a custom event of type objectChanged. Usually, I access the event type as a static class variable:</p>
<p><code><br />
var CustomEvents = {<br />
	OBJECT_CHANGED:"objectChanged";<br />
}<br />
jQuery(obj).bind(CustomEvents.OBJECT_CHANGED, listener);<br />
</code></p>
<p>That covers pretty much the basics oF OOP in JavaScript. A lot of metaphors (like private/protected/public accessors) may be missing here but I havent really found that to be too much of a problem. These metaphors have made my code a lot more manageable.</p>
<p><strong>Further reading:</strong><br />
<a href="http://ejohn.org/apps/learn/">John Resig&#8217;s list of lessons in advanced JavaScript</a> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.arpitonline.com/blog/2009/07/24/object-oriented-javascript-techniques/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
