04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Anonymous Functions<br />

An anonymous function is any function that doesn ’ t have a name; these are also sometimes referred<br />

to as lambda functions . Anonymous functions are incredibly powerful programming tools and can<br />

be used in any number of ways. Consider the following typical function declaration:<br />

function functionName(arg0, arg1, arg2) {<br />

//function body<br />

}<br />

As discussed earlier in the book, functions can be declared in this manner or defined as a function<br />

expression such as the following:<br />

var functionName = function(arg0, arg1, arg2) {<br />

//function body<br />

};<br />

Even though this example is logically equivalent to the previous one, there are some slight<br />

differences. The primary difference between function declarations and function expressions, of<br />

course, is that the former is loaded into the scope before code execution whereas the latter is<br />

unavailable until that particular line has been evaluated during code execution (discussed in<br />

Chapter 5 ). Another important distinction is that function declarations assign a name to the<br />

function, whereas function expressions actually create anonymous functions and assign them to a<br />

variable. This means the second example creates an anonymous function with three arguments<br />

and assigns it to the variable functionName , but the function itself doesn ’ t have a name assigned.<br />

It ’ s also possible to write an anonymous function like this:<br />

function (arg0, arg1, arg2){<br />

//function body<br />

}<br />

This code is completely valid. Of course, the function can never be called because there is no<br />

pointer to it. Anonymous functions are typically defined in this way when passing a function

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!