You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Functions, Closures, and Modules<br />
Later in this book, we will look at several functional tricks such as memoization<br />
and caching function calls. If you have reached here by quickly reading through the<br />
entire chapter, I would suggest that you stop for a while and contemplate on what<br />
we have discussed so far. The last few pages contain a ton of information and it will<br />
take some time for all this information to sink in. I would suggest that you reread<br />
this chapter before proceeding further. The next section will focus on closures and<br />
the module pattern.<br />
Closures<br />
Traditionally, closures have been a feature of purely functional programming<br />
languages. <strong>JavaScript</strong> shows its affinity with such functional programming<br />
languages by considering closures integral to the core language constructs. Closures<br />
are gaining popularity in mainstream <strong>JavaScript</strong> libraries and advanced production<br />
code because they let you simplify complex operations. You will hear experienced<br />
<strong>JavaScript</strong> programmers talking almost reverently about closures—as if they are<br />
some magical construct far beyond the reach of the intellect that common men<br />
possess. However, this is not so. When you study this concept, you will find closures<br />
to be very obvious, almost matter-of-fact. Till you reach closure enlightenment, I<br />
suggest you read and reread this chapter, research on the Internet, write code, and<br />
read <strong>JavaScript</strong> libraries to understand how closures behave—but do not give up.<br />
The first realization that you must have is that closure is everywhere in <strong>JavaScript</strong>. It<br />
is not a hidden special part of the language.<br />
Before we jump into the nitty-gritty, let's quickly refresh the lexical scope in<br />
<strong>JavaScript</strong>. We discussed in great detail how lexical scope is determined at the<br />
function level in <strong>JavaScript</strong>. Lexical scope essentially determines where and how all<br />
identifiers are declared and predicts how they will be looked up during execution.<br />
In a nutshell, closure is the scope created when a function is declared that allows the<br />
function to access and manipulate variables that are external to this function. In other<br />
words, closures allow a function to access all the variables, as well as other functions,<br />
that are in scope when the function itself is declared.<br />
Let's look at some example code to understand this definition:<br />
var outer = 'I am outer'; //Define a value in global scope<br />
function outerFn() { //Declare a a function in global scope<br />
console.log(outer);<br />
}<br />
outerFn(); //prints - I am outer<br />
[ 66 ]<br />
www.it-ebooks.info