06.07.2017 Views

Mastering JavaScript

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

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

Chapter 5<br />

ES6 modules<br />

Two separate module systems and different module loaders can be a bit<br />

intimidating. ES6 tries to solve this. ES6 has a proposed module specification that<br />

tries to keep the good aspects of both the CommonJS and AMD module patterns.<br />

The syntax of ES6 modules is similar to CommonJS and the ES6 modules support<br />

asynchronous loading and configurable module loading:<br />

//json_processor.js<br />

function processJSON(url) {<br />

...<br />

}<br />

export function getSiteContent(url) {<br />

return processJSON(url);<br />

}<br />

//main.js<br />

import { getSiteContent } from "json_processor.js";<br />

content=getSiteContent("http://google.com/");<br />

ES6 export lets you export a function or variable in a way similar to CommonJS.<br />

In the code where you want to use this imported function, you use the import<br />

keyword to specify from where you want the dependency to be imported. Once the<br />

dependency is imported, it can be used as a member of the program. We will discuss<br />

in later chapters how you can use ES6 in environments where ES6 is not supported.<br />

The factory pattern<br />

The factory pattern is another popular object creation pattern. It does not require the<br />

usage of constructors. This pattern provides an interface to create objects. Based on<br />

the type passed to the factory, that particular type of object is created by the factory.<br />

A common implementation of this pattern is usually using a class or static method of<br />

a class. The purposes of such a class or method are as follows:<br />

• It abstracts out repetitive operations when creating similar objects<br />

• It allows the consumers of the factory to create objects without knowing the<br />

internals of the object creation<br />

[ 131 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!