11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

A similar kind of nameless function doesn‘t even get assigned a name at any time. An<br />

anonymous function is one that cannot be further referenced after assignment or use. For<br />

example, we may want to sort arrays in a different manner than what the built-in sort() method<br />

provides (as we‘ll see in Chapter 7); in such cases, we may pass an anonymous function:<br />

var myArray = [2, 4, 2, 17, 50, 8];<br />

myArray.sort( function(x, y)<br />

{<br />

}<br />

);<br />

// function statements to do sort<br />

<strong>The</strong> creation of an anonymous function is in this case carried out by using a function literal.<br />

While the function is accessible to sort() because it was passed a parameter, the function is<br />

never bound to a visible name, so it is considered anonymous.<br />

Anonymous functions may be confusing, so you probably won‘t need to use them very often, if<br />

at all. Probably the only other place they are used in <strong>JavaScript</strong> is with event handlers, as<br />

shown here:<br />

<br />

<br />

<br />

Simple Event and Anonymous Function<br />

<br />

<br />

<br />

<br />

<br />

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

Saved successfully!

Ooh no, something went wrong!