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.

Functions, Closures, and Modules<br />

return {<br />

getSecret: getSecret,<br />

getPassCode: getPassCode<br />

};<br />

})();<br />

superModule.getSecret();<br />

superModule.getPassCode();<br />

This example satisfies both the conditions. Firstly, we create an IIFE or a named<br />

function to act as an outer enclosure. The variables defined will remain private<br />

because they are scoped in the function. We return the public functions to make sure<br />

that we have a closure over the private scope. Using IIFE in the module pattern will<br />

actually result in a singleton instance of this function. If you want to create multiple<br />

instances, you can create named function expressions as part of the module as well.<br />

We will keep exploring various facets of functional aspects of <strong>JavaScript</strong> and closures<br />

in particular. There can be a lot of imaginative uses of such elegant constructs. An<br />

effective way to understand various patterns is to study the code of popular libraries<br />

and practice writing these patterns in your code.<br />

Stylistic considerations<br />

As in the previous chapter, we will conclude this discussion with certain stylistic<br />

considerations. Again, these are generally accepted guidelines and not rules—feel<br />

free to deviate from them if you have reason to believe otherwise:<br />

• Use function declarations instead of function expressions:<br />

// bad<br />

const foo = function () {<br />

};<br />

// good<br />

function foo() {<br />

}<br />

• Never declare a function in a non-function block (if, while, and so on). Assign<br />

the function to a variable instead. Browsers allow you to do it, but they all<br />

interpret it differently.<br />

• Never name a parameter arguments. This will take precedence over the<br />

arguments object that is given to every function scope.<br />

[ 72 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!