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.

Chapter 5<br />

<strong>JavaScript</strong> offers flexible functions and objects that make it easy to create robust<br />

module systems. Function scopes help create namespaces that are internal for the<br />

module, and objects can be used to store sets of exported values.<br />

Before we start exploring the pattern itself, let's quickly brush up on a few concepts<br />

that we discussed earlier.<br />

We discussed object literals in detail. Object literals allow you to create name-value<br />

pairs as follows:<br />

var basicServerConfig = {<br />

environment: "production",<br />

startupParams: {<br />

cacheTimeout: 30,<br />

locale: "en_US"<br />

},<br />

init: function () {<br />

console.log( "Initializing the server" );<br />

},<br />

updateStartup: function( params ) {<br />

this.startupParams = params;<br />

console.log( this.startupParams.cacheTimeout );<br />

console.log( this.startupParams.locale );<br />

}<br />

};<br />

basicServerConfig.init(); //"Initializing the server"<br />

basicServerConfig.updateStartup({cacheTimeout:60,<br />

locale:"en_UK"}); //60, en_UK<br />

In this example, we are creating an object literal and defining key-value pairs to<br />

create properties and functions.<br />

In <strong>JavaScript</strong>, the module pattern is used very heavily. Modules help in mimicking<br />

the concept of classes. Modules allow us to include both public/private methods and<br />

variables of an object, but most importantly, modules restrict these parts from the<br />

global scope. As the variables and functions are contained in the module scope, we<br />

automatically prevent naming conflict with other scripts using the same names.<br />

Another beautiful aspect of the module pattern is that we expose only a public API.<br />

Everything else related to the internal implementation is held private within the<br />

module's closure.<br />

[ 125 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!