The Module Pattern
Modules are an integral piece of any robust application’s architecture and typically help in keeping the units of code for a project both cleanly separated and organized.
In JavaScript, there are several options for implementing modules. These include:
Object literal notation
The Module pattern
AMD modules
CommonJS modules
ECMAScript Harmony modules
We will be exploring the latter three of these options later on in the book in Chapter 11.
The Module pattern is based in part on object literals, so it makes sense to refresh our knowledge of them first.
Object Literals
In object literal notation, an object is described as a
set of comma-separated name/value pairs enclosed in curly braces
({}). Names inside the object may be either strings or
identifiers that are followed by a colon. There should be no comma used
after the final name/value pair in the object, as this may result in
errors.
varmyObjectLiteral={variableKey:variableValue,functionKey:function(){// ...};};
Object literals don’t require instantiation using the new operator, but shouldn’t be used at the
start of a statement, as the opening { may be interpreted as the beginning of a
block. Outside of an object, new members may be added to the object
literal using assignment as follows: myModule.property = "someValue";
Below, we can see a more complete example of a module defined using object literal notation:
varmyModule={myProperty:"someValue",// object literals can contain properties and methods.// ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access