Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Functions, Closures, and Modules<br />
Anonymous functions<br />
We introduced you to anonymous functions a bit earlier in this chapter, and as they're<br />
a crucial concept, we will take a detailed look at them. For a language inspired by<br />
Scheme, anonymous functions are an important logical and structural construct.<br />
Anonymous functions are typically used in cases where the function doesn't need<br />
to have a name for later reference. Let's look at some of the most popular usages of<br />
anonymous functions.<br />
Anonymous functions while creating an object<br />
An anonymous function can be assigned to an object property. When we do that,<br />
we can call that function with a dot (.) operator. If you are coming from a Java or<br />
other OO language background, you will find this very familiar. In such languages,<br />
a function, which is part of a class is generally called with a notation—Class.<br />
function(). Let's consider the following example:<br />
var santa = {<br />
say :function(){<br />
console.log("ho ho ho");<br />
}<br />
}<br />
santa.say();<br />
In this example, we are creating an object with a say property, which is an<br />
anonymous function. In this particular case, this property is known as a method and<br />
not a function. We don't need to name this function because we are going to invoke it<br />
as the object property. This is a popular pattern and should come in handy.<br />
Anonymous functions while creating a list<br />
Here, we are creating two anonymous functions and adding them to an array. (We<br />
will take a detailed look at arrays later.) Then, you loop through this array and<br />
execute the functions in a loop:<br />
<br />
var things = [<br />
function() { alert("ThingOne") },<br />
function() { alert("ThingTwo") },<br />
];<br />
for(var x=0; x