<?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>Keeping it simple</title>
	<atom:link href="http://nextwaveweb.co.uk/feed/" rel="self" type="application/rss+xml" />
	<link>http://nextwaveweb.co.uk</link>
	<description>Begin at the beginning and go on till you come to the end: then stop</description>
	<lastBuildDate>Fri, 21 Jan 2011 00:27:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>Simply Closures &#8211; Part II -&gt; The Meat</title>
		<link>http://nextwaveweb.co.uk/2011/01/simply-closures-part-ii-the-meat/</link>
		<comments>http://nextwaveweb.co.uk/2011/01/simply-closures-part-ii-the-meat/#comments</comments>
		<pubDate>Thu, 20 Jan 2011 22:54:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nextwaveweb.co.uk/?p=49</guid>
		<description><![CDATA[Scope Chains A function can see variables at it&#8217;s own level and all it&#8217;s ancestors. ie. see the following (n.b. none of the inner functions are closures) $(document).ready(function() { scopeChains(); }); var _global = true; function scopeChains() { var _inner1 = true; logVars('in scopeChains', _inner1); // _inner2 and _inner3 are out of scope function inner1() [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Scope Chains</strong></p>
<p>A function can see variables at it&#8217;s own level and all it&#8217;s ancestors.<br />
ie. see the following (n.b. none of the inner functions are closures)</p>
<pre name="code" class="javascript">

$(document).ready(function() {
    scopeChains();
});

var _global = true;
function scopeChains() {

    var _inner1 = true;
    logVars('in scopeChains', _inner1); // _inner2 and _inner3 are out of scope
    function inner1() {

        var _inner2 = true;
        logVars('in inner1', _inner1, _inner2); // _inner3 is out of scope
        function inner2() {

            var _inner3 = true;
            logVars('in inner2', _inner1, _inner2, _inner3);
        }
        inner2();
    }
    inner1();
}

function logVars(sFunctionName, inner1Var, inner2Var, inner3Var) {
    logLine('***** ' + sFunctionName + ' *****');
    logLine('_global = ' + _global);
    logLine('_inner1 = ' + (typeof (inner1Var) == 'undefined' ? 'undefined' : inner1Var));
    logLine('_inner2 = ' + (typeof (inner2Var) == 'undefined' ? 'undefined' : inner2Var));
    logLine('_inner3 = ' + (typeof (inner3Var) == 'undefined' ? 'undefined' : inner3Var));
    logLine('*****************************');
}

function logLine(sContent) {
    $('#txtArea').val($('#txtArea').val()
                            + sContent + '\r\n');
}
</pre>
<p><i>Outputted</i><br />
***** in scopeChains *****<br />
_global = true<br />
_inner1 = true<br />
_inner2 = undefined<br />
_inner3 = undefined<br />
*****************************<br />
***** in inner1 *****<br />
_global = true<br />
_inner1 = true<br />
_inner2 = true<br />
_inner3 = undefined<br />
*****************************<br />
***** in inner2 *****<br />
_global = true<br />
_inner1 = true<br />
_inner2 = true<br />
_inner3 = true<br />
*****************************</p>
<p><strong>Breaking the Chain</strong></p>
<p>How does an inner function break the chain?</p>
<ol>
<li>
By making itself global (omitting var)</p>
<pre name="code" class="javascript">
var n;
function f() {
  var b = 'b';
  n = function() {
    return b;
  };
}
// note, what about if we omit 'n='
</pre>
</li>
<li>
By having F return it to global space</p>
<pre name="code" class="javascript">
function f() {
  var b = 'b';
  return function() {
    return b;
  };
}
</pre>
</li>
</ol>
<p><strong>The concept of captured Variables</strong></p>
<p>The root of the chain is what holds all instances.<br />
I&#8217;m going to call it an instance stream, each broken chain has it&#8217;s own set of instances.</p>
<pre name="code" class="javascript">

function closureFunction(theVal) {
    return function() {
        // chain is broken, therefore
        // theVal is from a new instance stream
        log(theVal++);
    }
};

$(document).ready(function() {

    var arrFunctions = [];

    arrFunctions[0] = closureFunction(10);
    arrFunctions[1] = closureFunction(20);
    arrFunctions[2] = closureFunction(30);

    for (i = 0; i < 3; i++) {
        log('index = ' + i.toString());
        arrFunctions[i]();
        arrFunctions[i]();
    }

});

function log(sContent) {
    $('#txtArea').val($('#txtArea').val()
                            + sContent + '\r\n');
}
</pre>
<p><i>Outputted:</i><br />
index = 0<br />
10<br />
11<br />
index = 1<br />
20<br />
21<br />
index = 2<br />
30<br />
31</p>
<p><strong>To get parameter into closure space</strong></p>
<p>an argument to outer function essentially becomes a local variable,<br />
thereby we can pass an argument which will become it's own instance.</p>
<pre name="code" class="javascript">

function f(arg) {
  var n = function() {
    return arg++;
  };
  return n;
}
</pre>
<p>ie the arg is basically like a local like so:</p>
<pre name="code" class="javascript">

function f() {
  var arg = 2;
  var n = function() {
     return arg++;
  };
  return n;
}
</pre>
<p>so we have a parameter, which becomes it's own instance in the closure,</p>
<pre name="code" class="javascript">

$(document).ready(function() {

    var arrFunctions = [];
    var iCounter = 0;
    for (var i = 0; i < 5; i++) {
        iCounter = i * 10;
        arrFunctions[i] = (function(theCounter) {
            return function() {
                log(theCounter);
                theCounter++;
            }
        })(iCounter);
    }

    for (i = 0; i < 5; i++) {
        log('index = ' + i.toString());
        arrFunctions[i]();
        arrFunctions[i]();
    }

});

function log(sContent) {
    $('#txtArea').val($('#txtArea').val() + sContent + '\r\n');
}
</pre>
<p><i>outputs:</i><br />
index = 0<br />
0<br />
1<br />
index = 1<br />
10<br />
11<br />
index = 2<br />
20<br />
21<br />
index = 3<br />
30<br />
31<br />
index = 4<br />
40<br />
41</p>
<p>very useful for say ajax.<br />
imagine that _airlineDom, _flightNumDom, _opSuffixDom are input boxes.</p>
<p>e.g.</p>
<pre name="code" class="javascript">

doAjaxPost('updateAirlineName', _airline, true,
    (function() {
        return function(data) {
            successHandler.call(this, data);
            _airlineDom.val('');
            _flightNumDom.val('');
            _opSuffixDom.val('');
        }
    })(_airlineDom, _flightNumDom, _opSuffixDom),
    failureHandler);
</pre>
<p><a href="http://nextwaveweb.co.uk/2011/01/simply-closures-part-i-preliminaries/">Here is part one of the series</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nextwaveweb.co.uk/2011/01/simply-closures-part-ii-the-meat/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simply Closures &#8211; Part I -&gt; Preliminaries</title>
		<link>http://nextwaveweb.co.uk/2011/01/simply-closures-part-i-preliminaries/</link>
		<comments>http://nextwaveweb.co.uk/2011/01/simply-closures-part-i-preliminaries/#comments</comments>
		<pubDate>Wed, 19 Jan 2011 22:26:09 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://nextwaveweb.co.uk/?p=8</guid>
		<description><![CDATA[To cover closures I&#8217;m going to do as Lewis Carroll said; Begin at the beginning and go on till you come to the end: then stop. - The King, Alice in Wonderland This will make this a long post (update, posts!), but it will also hopefully set in place foundations that will make things much [...]]]></description>
			<content:encoded><![CDATA[<p>To cover closures I&#8217;m going to do as Lewis Carroll said;</p>
<blockquote><p>Begin at the beginning and go on till you come to the end: then stop.<br />
- <em>The King, Alice in Wonderland</em></p></blockquote>
<p>This will make this a long post (update, posts!), but it will also hopefully set in place foundations that will make things much easier to understand.</p>
<p><strong>Functions and Scope</strong></p>
<p>Functions are at the core of closures, as they govern scope.<br />
You see, most languages people are used to have block scope (C, C++, Objective-C, C#, Java etc)</p>
<p>example c# scope:</p>
<pre name="code" class="csharp">

if (true) {
    string theVar = "inner";
}
Console.WriteLine(theVar); // compilation error
                   // theVar is not in scope
</pre>
<p>In javascript this code is fine, as the code is in the same function.</p>
<pre name="code" class="javascript">

if (true) {
    var theVar = "inner";
}
alert(theVar); // this works
</pre>
<p>Functions can access their values and their parent functions values.<br />
We will clarify this further in part II of this blog series.  For now it is fine to note that block scope does not work in javascript, and that functions are what are crucial in delineating scope.</p>
<p>Therefore, functions in javascript are very important so we need to be specific about how we can declare them and call them.  This understanding will serve as a foundation for understanding the more powerful features of closures in javascript.</p>
<p>There are two ways to declare functions in javascript:</p>
<pre name="code" class="javascript">
// variation 1
function myFunction() {
   return 'hello world';
}

$(document).ready(function() {
   alert(myFunction());  // outputs hello world
   alert(window.myFunction());  // outputs hello world
});</pre>
<pre name="code" class="javascript">
// variation 2
var theFunction = myFunction() {
   return 'hello world';
}

$(document).ready(function() {
   alert(theFunction());  // outputs hello world
   alert(window.theFunction());  // outputs hello world
});</pre>
<p>under-the-hood javascript assigns globals to window object, the first variation is really a convenience shortcut to the second variation, where it assigns the function to globals.</p>
<p><strong>Self-Invoking Functions</strong></p>
<p>We can call functions as soon as we declare them, by using the following notation.<br />
This creates the function executes it then throws it away (ie we aren&#8217;t assigning the function to anything)</p>
<pre name="code" class="javascript">
(function(){
  alert('This function is called once straight-away');
})();</pre>
<p>The pattern being:</p>
<p><img src="http://www.nextwaveweb.co.uk/pictures/self-invoking.png" alt="self-invoking function" /></p>
<p><strong>Functions as Parameters (callback functions)</strong></p>
<p>We can also pass functions to be called in ours or other peoples functions:</p>
<pre name="code" class="javascript">
function addFunctionResults(a,b) {
   return a() + b();
}

function one() {
  return 1;
}

function two() {
  return 2;
}

$(document).ready(function() {
  alert(addFunctionResults(one, two));
});</pre>
<pre name="code" class="javascript">
// alternative version of the above
// using anonymous functions

function addFunctionResults(a,b) {
   return a() + b();
}

$(document).ready(function(e) {
  alert(addFunctionResults(function() { return 1; },
                           function() { return 2; })
         ); // returns 3
});</pre>
<p><strong>Inner Functions</strong></p>
<p>We can utilise an inner function, or we can return it by an explicit return or by assigning it to a variable in parent function space, the latter two cause a closure (we break the scope chain).  The preceding sentence will make sense once we begin talking about scope chains, for now, let us look at an example of inner functions that are utilised and inner functions that are returned.</p>
<pre name="code" class="javascript">

$(document).ready(function() {

    alert(a('hello world'));

});

function a(param) {
    function b(theInput) {
        return param;
    };
    return 'you said "' + b(param) + '"';
}  
</pre>
<p>Returning an inner function:</p>
<pre name="code" class="javascript">
  // returning an inner function
  function a() {
    alert('returning inner function');
    return function() {
      alert('b');
    };
  }</pre>
<pre name="code" class="javascript">
var innerFunction = a();
innerFunction();

// or if we do not need to save
// a reference to function (ie call only once)
a()();</pre>
<p>So, when we return an inner function, we call it once to get the inner function, then we call again to call the inner function.<br />
This trick is used by people to make private initialisations in a function.</p>
<pre name="code" class="javascript">

function initA() {
    alert('A!'); // stuff here is private init
    return function() {
        alert('B!');
    };
}

$(document).ready(function() {
    var func = initA(); // init // outputs A!
    func(); // call function once // outputs B!
    func(); // call function a second time // outputs B!
});  
</pre>
<p>Or as a variation, here we can do init and overwrite our function:</p>
<pre name="code" class="javascript">

function a() {
    alert('A!'); // stuff here is private init
    a = function() {
        alert('B!');
    };
}

$(document).ready(function() {
    a(); // init // outputs A!
    a(); // call function once // outputs B!
    a(); // call function a second time // outputs B!
});  
</pre>
<p><a href="http://nextwaveweb.co.uk/2011/01/simply-closures-part-ii-the-meat/">Here is part 2 of this series</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nextwaveweb.co.uk/2011/01/simply-closures-part-i-preliminaries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

