<?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>puremedia &#187; javascript</title>
	<atom:link href="http://blog.puremedia-online.de/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.puremedia-online.de</link>
	<description>beyond applications and software</description>
	<lastBuildDate>Mon, 01 Mar 2010 09:48:54 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>JavaScript summed up #9: Memoization</title>
		<link>http://blog.puremedia-online.de/2009/10/01/javascript-summed-up-9-currying/</link>
		<comments>http://blog.puremedia-online.de/2009/10/01/javascript-summed-up-9-currying/#comments</comments>
		<pubDate>Thu, 01 Oct 2009 07:00:41 +0000</pubDate>
		<dc:creator>Tobias Günther</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.puremedia-online.de/?p=219</guid>
		<description><![CDATA[
			
				
			
		
Doing the same work twice is never a good thing. Knowing that, a pattern called &#8220;Memoization&#8221; can help you avoid this. It&#8217;s about building functions that remember their previous outputs/return values.
Let&#8217;s pretend you&#8217;ve written a function that takes a number as an argument and multiplies it with, say, 2.5. Not exactly heavy computational work, but [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F10%2F01%2Fjavascript-summed-up-9-currying%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F10%2F01%2Fjavascript-summed-up-9-currying%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Doing the same work twice is never a good thing. Knowing that, a pattern called &#8220;Memoization&#8221; can help you avoid this. It&#8217;s about building functions that remember their previous outputs/return values.<span id="more-219"></span></p>
<p>Let&#8217;s pretend you&#8217;ve written a function that takes a number as an argument and multiplies it with, say, 2.5. Not exactly heavy computational work, but for the sake of clearness&#8230;</p>
<pre>var multiplierFunction( myNumber ) {
    return myNumber * 2.5;
}</pre>
<p>If you call the function 10 times, it will have to do the computation 10 times. In cases where there&#8217;s some more effort inside the function, this can be a waste of performance.</p>
<p>To reimplement it using memoization, you just need to provide a plain JavaScript object that remembers previous results. Here, we call it &#8220;memo&#8221; and attach it right to the function:</p>
<pre>multiplierFunction = function( myNumber ){
    if ( typeof multiplierFunction.memo[myNumber] != "undefined" ){
         return multiplierFunction.memo[myNumber];
    }
    // the following code will only be executed if necessary
    // i.e. if the same calculation wasn't done before
    multiplierFunction.memo[myNumber] = myNumber * 2.5;
    return multiplierFunction.memo[myNumber];
}
multiplierFunction.memo = {};</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.puremedia-online.de/2009/10/01/javascript-summed-up-9-currying/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaScript summed up #8: Reflection</title>
		<link>http://blog.puremedia-online.de/2009/09/24/javascript-summed-up-8-reflection/</link>
		<comments>http://blog.puremedia-online.de/2009/09/24/javascript-summed-up-8-reflection/#comments</comments>
		<pubDate>Thu, 24 Sep 2009 07:00:28 +0000</pubDate>
		<dc:creator>Tobias Günther</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.puremedia-online.de/?p=212</guid>
		<description><![CDATA[
			
				
			
		
Inspecting objects at runtime is what&#8217;s called &#8220;reflection&#8221;. Maybe you want to know &#8211; at runtime &#8211; what methods an object has or what type of object it is. You&#8217;ve got a couple of tools at hand to do this in JavaScript:
typeof &#38; constructor
Before you read on, you should be familiar with both the &#8220;typeof&#8221; [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F09%2F24%2Fjavascript-summed-up-8-reflection%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F09%2F24%2Fjavascript-summed-up-8-reflection%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Inspecting objects at runtime is what&#8217;s called &#8220;reflection&#8221;. Maybe you want to know &#8211; at runtime &#8211; what methods an object has or what type of object it is. You&#8217;ve got a couple of tools at hand to do this in JavaScript:<span id="more-212"></span></p>
<h3>typeof &amp; constructor</h3>
<p>Before you read on, you should be familiar with both the &#8220;typeof&#8221; keyword and the &#8220;constructor&#8221; property. If you&#8217;re not (yet) familiar, you can get yourself up to speed by reading <a href="http://blog.puremedia-online.de/2009/08/20/javascript-recapitulated-3-type-checking/">my previous post about type checking.</a></p>
<h3>for&#8230;in</h3>
<p>With for&#8230;in you can iterate over the properties of an object. So if you want to know which methods an object has, you can write something like this:</p>
<pre>for ( prop in myObject ){
    if (typeof myObject[prop] == 'function') {
        // ...that's a function
    }
}</pre>
<h3>hasOwnProperty</h3>
<p>Iterating through an object&#8217;s property is fine &#8211; unless you need to know if it&#8217;s exactly _this_ object, and not one of its parents in the inheritance hiearchy, that has this property.<br />
To find out just that, you can use &#8220;hasOwnProperty&#8221; which doesn&#8217;t look up in the prototype-chain, but only in the very object you&#8217;re calling the method upon:</p>
<pre>
<pre>// true, if a property named "myMethod" exists in the object itself
myObject.hasOwnProperty('myMethod');</pre>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.puremedia-online.de/2009/09/24/javascript-summed-up-8-reflection/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JavaScript summed up #7: Dynamic code</title>
		<link>http://blog.puremedia-online.de/2009/09/17/javascript-summed-up-7-dynamic-code/</link>
		<comments>http://blog.puremedia-online.de/2009/09/17/javascript-summed-up-7-dynamic-code/#comments</comments>
		<pubDate>Thu, 17 Sep 2009 07:00:15 +0000</pubDate>
		<dc:creator>Tobias Günther</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.puremedia-online.de/?p=203</guid>
		<description><![CDATA[
			
				
			
		
JavaScript can be a very dynamic language. To prove this, today we&#8217;ll discuss two techniques: dynamic code generation in general and &#8220;branching&#8221; (a special form).
Dynamic method generation
JavaScript allows you to add, change, or remove functions dynamically at runtime. Since functions are just objects in JavaScript (see my previous post on functions), you could just add [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F09%2F17%2Fjavascript-summed-up-7-dynamic-code%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F09%2F17%2Fjavascript-summed-up-7-dynamic-code%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>JavaScript can be a very dynamic language. To prove this, today we&#8217;ll discuss two techniques: dynamic code generation in general and &#8220;branching&#8221; (a special form).<span id="more-203"></span></p>
<h3>Dynamic method generation</h3>
<p>JavaScript allows you to add, change, or remove functions dynamically at runtime. Since functions are just objects in JavaScript (see my <a href="http://blog.puremedia-online.de/2009/08/06/javascript-recapulated-1-functions/">previous post on functions</a>), you could just add a new one like this:</p>
<pre>var someVariable = "Dynamic";
this["my"+ someVariable +"Function"] = function(){
    // your code
}</pre>
<p>As soon as these lines get executed, you have a function called &#8220;myDynamicFunction&#8221; at hand.</p>
<p>A little more complex (and more useful) example comes from John Resig: he shows a way to create &#8220;getter&#8221; and &#8220;setter&#8221; methods for the properties of an object. In this example, a &#8220;User&#8221; object, that expects an object with some properties upon initialization. For these properties, we then generate setters and getters:</p>
<pre>function User(properties ) {
  self = this;
  // iterate through the properties of the object
  for ( var property in properties ) {
    (function(property){
       // create a new getter for the property
       self["get_" + property] = function() {
         return properties[property];
       };
       // create a new setter for the property
       self["set_" + property] = function(val) {
         properties[property] = val;
         return self;
       };
    })(property);
  }
}</pre>
<p>EDIT: thanks to &#8220;tester&#8217;s&#8221; comment with a correction of the above code!</p>
<h3>Branching</h3>
<p>Branching can be used to override an existing function with an optimized version on first run. A good example scenario is writing cross-browser code.<br />
Imagine you have to write a function that does one thing when run in one browser, and totally different things in another one.</p>
<pre>function xyz(){
   if ( a == b ){
      // do one thing
   }else{
      // do another thing
   }
}</pre>
<p>You would have the (in this example case admittedly small&#8230;) performance hit of at least running the condition code to distinguish between the two browsers. If the condition is quite expensive to run, or if the code will be run very very often (so that even a minimal performance improvement is desired), branching comes in handy.<br />
Instead of checking the condition each time, it is only checked one on the first call of the function. Then, the function is rewritten &#8211; without the condition:</p>
<pre>function xyz(){
   if ( a == b ){
      // override the function with the code for case A!
      xyz = function() { ...code for this case... };
   }else{
<pre>      // override the function with the code for case B!
      xyz = function() { ...code for that case... };
   }
}</pre>
</pre>
<p>From the second time on, when xyz is called, there is no condition &#8211; just plain optimized code. Of course, this means that the condition should not change during runtime; it should be always the same, because it won&#8217;t get checked a second time.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.puremedia-online.de/2009/09/17/javascript-summed-up-7-dynamic-code/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>JavaScript summed up #6: Reflow</title>
		<link>http://blog.puremedia-online.de/2009/09/10/javascript-summed-up-6-reflow/</link>
		<comments>http://blog.puremedia-online.de/2009/09/10/javascript-summed-up-6-reflow/#comments</comments>
		<pubDate>Thu, 10 Sep 2009 07:00:38 +0000</pubDate>
		<dc:creator>Tobias Günther</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.puremedia-online.de/?p=198</guid>
		<description><![CDATA[
			
				
			
		
Actually, I planned to write an article about &#8220;Reflow&#8221; &#8211; an important performance-relevant topic in every highly interactive JavaScript application.
But, as I was doing research for the article, I noticed that there are already a handful of very good articles and resources out there. So, instead of re-describing   the wheel, I highly recommend [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F09%2F10%2Fjavascript-summed-up-6-reflow%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F09%2F10%2Fjavascript-summed-up-6-reflow%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Actually, I planned to write an article about &#8220;Reflow&#8221; &#8211; an important performance-relevant topic in every highly interactive JavaScript application.<br />
But, as I was doing research for the article, I noticed that there are already a handful of very good articles and resources out there. So, instead of re-describing <img src='http://blog.puremedia-online.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  the wheel, I highly recommend reading through these:</p>
<ul>
<li><a href="http://www.mozilla.org/newlayout/doc/reflow.html">http://www.mozilla.org/newlayout/doc/reflow.html</a></li>
<li><a href="http://dev.opera.com/articles/view/efficient-javascript/?page=3#reflow">http://dev.opera.com/articles/view/efficient-javascript/?page=3#reflow</a></li>
<li><a href="http://www.stubbornella.org/content/2009/03/27/reflows-repaints-css-performance-making-your-javascript-slow/">http://www.stubbornella.org/content/2009/03/27/reflows-repaints-css-performance-making-your-javascript-slow/</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.puremedia-online.de/2009/09/10/javascript-summed-up-6-reflow/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript summed up #5: Configuration values</title>
		<link>http://blog.puremedia-online.de/2009/09/03/javascript-summed-up-5-configuration-values/</link>
		<comments>http://blog.puremedia-online.de/2009/09/03/javascript-summed-up-5-configuration-values/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 07:00:28 +0000</pubDate>
		<dc:creator>Tobias Günther</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.puremedia-online.de/?p=189</guid>
		<description><![CDATA[
			
				
			
		
Maintaining and keeping code clean is always a challenge. And JavaScript is not different here.
In complex applications, JavaScript combines a great deal of application logic with classic GUI concerns. Therefore, temptations are high to put things like labels/texts into code (i.e. hard-coding the values). But already the term &#8220;hard-coded&#8221; should let you think twice.
A better [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F09%2F03%2Fjavascript-summed-up-5-configuration-values%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F09%2F03%2Fjavascript-summed-up-5-configuration-values%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Maintaining and keeping code clean is always a challenge. And JavaScript is not different here.</p>
<p>In complex applications, JavaScript combines a great deal of application logic with classic GUI concerns. Therefore, temptations are high to put things like labels/texts into code (i.e. hard-coding the values). But already the term &#8220;hard-coded&#8221; should let you think twice.</p>
<p><span id="more-189"></span>A better solution is to keep things like</p>
<ul>
<li>labels / texts</li>
<li>URLs</li>
<li>configurable values</li>
</ul>
<p>out of your functions.</p>
<p>Using a single &#8220;configuration&#8221; object in JavaScript is a simple and comfortable solution to this problem:</p>
<pre>MyNamespace.configuration = {
    uris: {
        data_loading_url: 'dummy_data.json',
        details_url: '/projects/###ID###/show'
    },
    labels : {
        date_button: 'Go to date',
    }
}</pre>
<p>Using those prepared values in code is then as easy as pie:</p>
<pre>var link_element = '&lt;a href="' + MyNamespace.configuration.uris.data_loading_url + '"&gt;';
link_element += MyNamespace.configuration.labels.date_button;
link_element += '&lt;/a&gt;';</pre>
<p>This makes changing those values easy and safe &#8211; and separates changeable content (configuration values) from your logic/code.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.puremedia-online.de/2009/09/03/javascript-summed-up-5-configuration-values/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript summed up #4: Namespaces</title>
		<link>http://blog.puremedia-online.de/2009/08/27/javascript-summed-up-4-namespaces/</link>
		<comments>http://blog.puremedia-online.de/2009/08/27/javascript-summed-up-4-namespaces/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 07:00:42 +0000</pubDate>
		<dc:creator>Tobias Günther</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.puremedia-online.de/?p=181</guid>
		<description><![CDATA[
			
				
			
		
In currently popular versions of JavaScript, there&#8217;s no native concept of namspaces, like in C#, Java and Co.
But namespaces are important when it comes to larger applications and/or using third party code. You risk to have conflicts with other code (being it your own code or third party code) that is named the same. Unexpected [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F08%2F27%2Fjavascript-summed-up-4-namespaces%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F08%2F27%2Fjavascript-summed-up-4-namespaces%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>In currently popular versions of JavaScript, there&#8217;s no native concept of namspaces, like in C#, Java and Co.<br />
But namespaces are important when it comes to larger applications and/or using third party code. You risk to have conflicts with other code (being it your own code or third party code) that is named the same. Unexpected behaviour, to say it politely, can be the result (apart from polluting the global namespace with a lot of variables is just not very nice&#8230;).<br />
So we know we need a way to simulate namespaces in JavaScript, too.</p>
<p><span id="more-181"></span>It proves to be as simple as creating one global object that hosts all your code:</p>
<pre>var FOCUS = {};
FOCUS.firstFunction = function(){
   // your code, not polluting the global namespace...
}</pre>
<p>There might be situations when you don&#8217;t know if you&#8217;ve already created a certain namespace. You can check it (and create it, if it doesn&#8217;t exist, yet) easily:</p>
<pre>if ( typeof FOCUS == 'undefined' ) var FOCUS = {};</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.puremedia-online.de/2009/08/27/javascript-summed-up-4-namespaces/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaScript summed up #3: Type checking</title>
		<link>http://blog.puremedia-online.de/2009/08/20/javascript-summed-up-3-type-checking/</link>
		<comments>http://blog.puremedia-online.de/2009/08/20/javascript-summed-up-3-type-checking/#comments</comments>
		<pubDate>Thu, 20 Aug 2009 07:00:24 +0000</pubDate>
		<dc:creator>Tobias Günther</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.puremedia-online.de/?p=172</guid>
		<description><![CDATA[
			
				
			
		
Since JavaScript currently is a dynamically typed language, the topic of type checking is quite interesting. In certain situations it&#8217;s rather important to know of which type the object at hand really is.
Here, we have some dummy objects that we want to type-check:
var num = 12;
var string = "Hello World";
var array = [1,2,3];
var object = [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F08%2F20%2Fjavascript-summed-up-3-type-checking%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F08%2F20%2Fjavascript-summed-up-3-type-checking%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Since JavaScript currently is a dynamically typed language, the topic of type checking is quite interesting. In certain situations it&#8217;s rather important to know of which type the object at hand really is.</p>
<p>Here, we have some dummy objects that we want to type-check:</p>
<pre>var num = 12;
var string = "Hello World";
var array = [1,2,3];
var object = { firstProp: 1, secondProp: 2 };
function Car(){};
var car = new Car();</pre>
<p>Let&#8217;s look at two different ways to check the type of an object.</p>
<p><span id="more-172"></span></p>
<h3>typeof</h3>
<p>With the help of the typeof keyword, you have one possibility to check an object&#8217;s type. An example usage could look like this:</p>
<pre>if ( typeof num == "number" ) ... // true
if ( typeof array == "array") ... // false, because "object" is returned
if ( typeof car == "Car" ) ... // false, because "object" is returned</pre>
<p>The typeof way works nicely with most object types. But unfortunately, it leaves a little uncertainty when dealing with types like Array or your own types (like &#8220;Car&#8221; in our dummy examples). That&#8217;s because typeof only returns the not so helpful &#8220;object&#8221; in those cases. So let&#8217;s look at another way&#8230;</p>
<h3>constructor</h3>
<p>Every JavaScript object has a property called &#8220;constructor&#8221; &#8211; which proves to be helpful in our case:</p>
<pre>if ( car.constructor == Car ) ... // true
if ( array.constructor == Array ) ... // true</pre>
<p>The constructor-variant has the advantage of returning a reference to the function that was used when creating the object in question &#8211; not just &#8220;object&#8221;. Since a reference is returned, you have to remember not to use quotation marks (in contrast to the typeof variant, where a string is returned).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.puremedia-online.de/2009/08/20/javascript-summed-up-3-type-checking/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JavaScript summed up #2: Closures</title>
		<link>http://blog.puremedia-online.de/2009/08/13/javascript-summed-up-2-closures/</link>
		<comments>http://blog.puremedia-online.de/2009/08/13/javascript-summed-up-2-closures/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 07:00:49 +0000</pubDate>
		<dc:creator>Tobias Günther</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.puremedia-online.de/?p=165</guid>
		<description><![CDATA[
			
				
			
		
Closures are a vital part of JavaScript&#8217;s dynamic nature. Without it, a lot of things would work totally different. Because of this significance, it&#8217;s important to thoroughly understand closures.
So, what _is_ a closure, really?


A closure simply is a function inside of another function (an inner function, if you will)&#8230;
&#8230;that has access to the context of [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F08%2F13%2Fjavascript-summed-up-2-closures%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F08%2F13%2Fjavascript-summed-up-2-closures%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Closures are a vital part of JavaScript&#8217;s dynamic nature. Without it, a lot of things would work totally different. Because of this significance, it&#8217;s important to thoroughly understand closures.</p>
<p>So, what _is_ a closure, really?</p>
<p><span id="more-165"></span></p>
<ul>
<li>A closure simply is a function inside of another function (an inner function, if you will)&#8230;</li>
<li>&#8230;that has access to the context of its outer/enclosing function&#8230;</li>
<li>[now it gets interesting!] &#8230;even if the outer function has already terminated.</li>
</ul>
<p>Okay, let&#8217;s have an example:</p>
<pre>var myFunction = function(text){
     setTimeout( function(){
         alert(text);
     }, 1000);
}</pre>
<p>Here, the case is quite clear: when the inner function is called through the timeout, the outer function (&#8221;myFunction&#8221;) has long terminated (about 1 sec. ago). Still, the inner function has access to the variables of its parent function (the variable &#8220;text&#8221;, in this case).</p>
<p>Some more examples should make the use and importance of closures a little clearer:</p>
<h3>(function(){})();</h3>
<p>Used in many modern AJAX libraries, this construct can be quite puzzling on first sight. So let&#8217;s deconstruct it outside-in, to see what&#8217;s it all about.<br />
The (&#8230;)() construct is used to hide the contained code from the outside world (and scope). Try this example for yourself:</p>
<pre>function testFunc(){};
(function test2Func(){});
console.log(window.testFunc);
console.log(window.test2Func);</pre>
<p>The first one, testFunc, is visible to the outside world (window.x), the second is hidden from it. So (&#8230;)() can be used to avoid polluting the global namespace.</p>
<p>The anonymous function inside of the parentheses is used to create and execute the desired code in one go. Additionally, we have access to all outside variables &#8211; because a function always has access to it&#8217;s surrounding context.</p>
<h3>private variables</h3>
<p>As you probably know, the JavaScript language currently doesn&#8217;t have the concept of public/private/protected members. But with closures, we can simulate this system:</p>
<pre>function publicPrivate(){
     var privateProp = "This one is private";
     var privateFunc = function(){ console.log("From private func:", privateProp); };
     privateFunc();
     return {
        publicProp: "This one is public"
     }
}
var myObj = new publicPrivate();
console.log("From outside:", myObj.publicProp);
console.log("From outside:", myObj.privateProp);</pre>
<p>The last console.log will return undefined in Firebug, because privateProp can&#8217;t be accessed from outside. The first one, from inside our publicPrivate function, will return &#8220;This is private&#8221; because we&#8217;re calling our private member from inside.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.puremedia-online.de/2009/08/13/javascript-summed-up-2-closures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript summed up #1: Functions</title>
		<link>http://blog.puremedia-online.de/2009/08/06/javascript-recapulated-1-functions/</link>
		<comments>http://blog.puremedia-online.de/2009/08/06/javascript-recapulated-1-functions/#comments</comments>
		<pubDate>Thu, 06 Aug 2009 16:57:25 +0000</pubDate>
		<dc:creator>Tobias Günther</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.puremedia-online.de/?p=153</guid>
		<description><![CDATA[
			
				
			
		
PREFACE: This is the first post in a series of posts about JavaScript. There&#8217;ll be roughly one post per week in the next couple of weeks (don&#8217;t ask me, yet, how many weeks I&#8217;m going to hang in there &#8211; a couple, at least!  .
The goal is to give a thorough overview of some [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F08%2F06%2Fjavascript-recapulated-1-functions%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.puremedia-online.de%2F2009%2F08%2F06%2Fjavascript-recapulated-1-functions%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p><strong>PREFACE:</strong> This is the first post in a series of posts about JavaScript. There&#8217;ll be roughly one post per week in the next couple of weeks (don&#8217;t ask me, yet, how many weeks I&#8217;m going to hang in there &#8211; a couple, at least! <img src='http://blog.puremedia-online.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> .<br />
The goal is to give a thorough overview of some important core aspects of the language &#8211; ranging from building blocks like closures to best practices like unit testing.<br />
Honor to whom honor is due &#8211; I&#8217;ve not invented these concepts and best practices but learned them from some of the best &#8211; most notably folks like John Resig or Douglas Crockford.</p>
<p>The first post is about the concepts of &#8220;functions&#8221; in JavaScript.<br />
<span id="more-153"></span></p>
<p><strong>NOTE</strong>: In a lot of examples, you will see the expression &#8220;console.log(&#8230;)&#8221;. This causes Firebug to output something on its console. So please have the <a href="http://getfirebug.com/">Firebug plugin</a> for Mozilla Firefox ready when you&#8217;re playing with the code.</p>
<p>==============</p>
<p>Functions are a core part of JavaScript. Admittedly, functions are a core part of almost every language. But since JavaScript doesn&#8217;t have the classic implementation of classes (more on that in a later post), functions become even more important.</p>
<p>First of all it&#8217;s important to know that functions are indeed objects in JavaScript. Because they&#8217;re objects, quite a few very JavaScriptish things are possible &#8211; that might not be common in other languages.</p>
<ul>
<li>Functions can be stored in variables
<pre>var myFunction = function(){
    alert("Hello world");
};</pre>
</li>
<li>Functions can return functions
<pre>var my2ndFunction = function(){
    return myFunction;
};</pre>
</li>
<li>Functions can be arguments to other functions
<pre>var alertThroughFunctionArg = function(arg){
    arg();
};
var argFunction = function(){
    alert("Number 4");
};
alertThroughFunctionArg(argFunction);
// ===&gt; "Number 4"</pre>
</li>
<li>Functions can have properties<br />
This might seem a little strange. A function that has properties?? Yes, you&#8217;re right. If you remember that a function is „just“ an object, it sounds reasonable that a function can have properties.</p>
<pre>function calledFunction(){
    calledFunction.called += 1;
};
calledFunction.called = 0;

calledFunction();
calledFunction();
calledFunction();
console.log(calledFunction.called);
// ===&gt; 3</pre>
</li>
<li>Functions have a prototype attribute (more on that in a later post)</li>
</ul>
<h3>„arguments“ variable</h3>
<p>Every function has a variable called „arguments“.  It&#8217;s a array-like collection of all the arguments the function has received. „Array-like“ because you can access its items, but not manipulate it. It can be used to implement what&#8217;s known as „function overloading“ in other languages.</p>
<h3>„length“ property</h3>
<p>There&#8217;s another freeby regarding functions: the length property, which also every function has. It contains the number of expected (defined arguments in the function signature -  not the number of really passed arguments when called!).</p>
<pre>function lengthFunction(a, b, c){
    console.log(lengthFunction.length);
};</pre>
<p>Calling lengthFunction would show „3“ in Firebug.</p>
<h3>return value</h3>
<p>Every function has a return value. Whether you&#8217;re explicitly stating „return“ or not. If you&#8217;re not returning an explicit value, „undefined“ is returned. This is similar to what is delivered to the function body, if a parameter wasn&#8217;t provided at all at call time &#8211; „undefined“.</p>
<h3>scope</h3>
<p>Unlike other C-syntaxed languages, JavaScript has no „block-scope“. Variables are visible inside the function where they&#8217;re defined. If you define them inside of a block, like an if-statement, they continue to be visible even if the block is left. So, JavaScript only cares about function-scope, there&#8217;s no block-scope.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.puremedia-online.de/2009/08/06/javascript-recapulated-1-functions/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>
