<?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>Traversal &#187; jQuery</title>
	<atom:link href="http://traversal.com.au/category/jquery/feed/" rel="self" type="application/rss+xml" />
	<link>http://traversal.com.au</link>
	<description></description>
	<lastBuildDate>Mon, 30 Jan 2012 04:59:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>JavaScript global closures and jQuery</title>
		<link>http://traversal.com.au/blog/2009/03/28/jquery-global-closures/</link>
		<comments>http://traversal.com.au/blog/2009/03/28/jquery-global-closures/#comments</comments>
		<pubDate>Sat, 28 Mar 2009 04:32:53 +0000</pubDate>
		<dc:creator>Travis Hensgen</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Snippets]]></category>

		<guid isPermaLink="false">http://local.traversal.com.au/?p=103</guid>
		<description><![CDATA[Learn how to use JavaScript anonymous function wrappers and their jQuery variants to keep the global variable space tidy.]]></description>
			<content:encoded><![CDATA[<p>When adding JavaScript behaviours to your web site or application, keeping the global variable scope as clean as possible is a good practice to avoid naming conflicts, especially if you are using third party code from multiple sources.</p>
<h3>The anonymous function wrapper</h3>
<p><em>Closures</em> in JavaScript allow us to keep the global scope tidy &#8211; we can create one by declaring an anonymous function in the global scope, and then immediately calling that function, like so:</p>
<pre class="brush: js">
(function() {
// variables and functions declared here are not visible in global scope

})();
</pre>
<p>The syntax is strange but if you break it down it makes sense: we place brackets <em>around</em> the function declaration so that it&#8217;s clear to JavaScript that we are then operating on the function as if it&#8217;s a variable. </p>
<p>It might help to remember that in JavaScript, we can <em>also</em> declare a function like this:</p>
<pre class="brush: js">
var myFunc = function() { // function body
};

// now we can call the function like normal:
myFunc();
</pre>
<p>So, all the brackets around the function declaration do is take out the unnecessary step of assigning to an intermediate variable. Then, we immediately call the function with <code>()</code>, just like we did above with <code>myFunc</code> &#8211; calling the function ensures that the code is actually executed, which is rather important if we actually want to <em>achieve anything</em> inside the wrapper! <img src='http://traversal.com.au/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' />  </p>
<p>The beauty of these anonymous function wrappers is that once you memorize the syntax, you don&#8217;t really have to think too hard about the mechanics of them. <img src='http://traversal.com.au/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>The jQuery version</h3>
<p>jQuery works hard to avoid polluting the global variable space by design. Out of the box, it only contains 2 global variables: the <code>jQuery</code> object itself, and its alias shorthand <code>$</code>. Building on the standard anonymous function wrapper, we can use the version illustrated below which has the additional benefit of ensuring that any use of <code>$</code> inside the wrapper will be a call to the <code>jQuery</code> object and not to <code>$</code> in another library such as Prototype or MooTools, if those happen to be used on the same page.</p>
<pre class="brush: js">
(function($) {
// code in here can safely use $, knowing it will reference jQuery

})(jQuery);
</pre>
<p>Here, the <code>$</code> shorthand is a named parameter in our anonymous function, whose value becomes the <code>jQuery</code> object in our immediate call &#8211; <code>(jQuery)</code>. Importantly, the value of <code>$</code> <em>outside</em> the function is retained - this works because with with JavaScript closures, function parameter variables are <em>also</em> local in scope to the code in that closure, and any values with the same name outside that closure are not affected.</p>
<p><strong>There is one gotcha:</strong> if you are using <em>jQuery</em> with <em>Prototype</em> or <em>MooTools</em>, it&#8217;s easiest to include <em>jQuery</em> <strong>before</strong> the other library, so that it doesn&#8217;t override the value of <code>$</code> <strong>outside</strong> the anonymous function. If for whatever reason you <em>must</em> include <em>jQuery</em> after <em>Prototype</em> or <em>MooTools</em>, you can call <code>jQuery.noConflict()</code> before you call the <code>$</code> shortcut in the other library &#8211; more information on this is available in the jQuery documentation <a href="http://docs.jquery.com/Using_jQuery_with_Other_Libraries">here</a>.</p>
<p>Once again though, the beauty of the jQuery wrapper code is that once you memorize it, the mechanics of how and why it works don&#8217;t really need to be fresh in your mind. But it still doesn&#8217;t hurt to know the how and why. <img src='http://traversal.com.au/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  </p>
]]></content:encoded>
			<wfw:commentRss>http://traversal.com.au/blog/2009/03/28/jquery-global-closures/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>


<!-- W3 Total Cache: Page cache debug info:
Engine:             disk (enhanced)
Key:                category/jquery/feed/_index.html
Caching:            enabled
Status:             not cached
Creation Time:      0.304s
Header info:
X-Pingback:         http://traversal.com.au/xmlrpc.php
ETag:               "64c6a36058dc032fbf8154666f79bb0d"
X-Powered-By:       W3 Total Cache/0.9.1.3
Content-Type:       text/xml; charset=UTF-8
Last-Modified:      Mon, 06 Feb 2012 20:47:44 GMT
Vary:               Accept-Encoding, Cookie
Content-Encoding:   gzip
-->
