06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

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

Anonymous functions as a parameter to<br />

another function<br />

This is one of the most popular patterns and you will find such code in most<br />

professional libraries:<br />

// function statement<br />

function eventHandler(event){<br />

event();<br />

}<br />

eventHandler(function(){<br />

//do a lot of event related things<br />

console.log("Event fired");<br />

});<br />

Chapter 2<br />

You are passing the anonymous function to another function. In the receiving<br />

function, you are executing the function passed as a parameter. This can be very<br />

convenient if you are creating single-use functions such as object methods or event<br />

handlers. The anonymous function syntax is more concise than declaring a function<br />

and then doing something with it as two separate steps.<br />

Anonymous functions in conditional logic<br />

You can use anonymous function expressions to conditionally change behavior. The<br />

following example shows this pattern:<br />

var shape;<br />

if(shape_name === "SQUARE") {<br />

shape = function() {<br />

return "drawing square";<br />

}<br />

}<br />

else {<br />

shape = function() {<br />

return "drawing square";<br />

}<br />

}<br />

alert(shape());<br />

Here, based on a condition, we are assigning a different implementation to the shape<br />

variable. This pattern can be very useful if used with care. Overusing this can result<br />

in unreadable and difficult-to-debug code.<br />

[ 65 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!