Modular Programming with JavaScript - Sasan Seydnejad - E-Book

Modular Programming with JavaScript E-Book

Sasan Seydnejad

0,0
38,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Modularize your JavaScript code for better readability, greater maintainability, and enhanced testability

About This Book

  • Design and build fully modular, modern JavaScript applications using modular design concepts
  • Improve code portability, maintainability, and integrity while creating highly scalable and responsive web applications
  • Implement your own loosely coupled code blocks that can power highly maintainable and powerful applications in a flexible and highly responsive modular architecture

Who This Book Is For

If you are an intermediate to advanced JavaScript developer who has experience of writing JavaScript code but probably not in a modular, portable manner, or you are looking to develop enterprise level JavaScript applications, then this book is for you.

A basic understanding of JavaScript concepts such as OOP, prototypal inheritance, and closures is expected.

What You Will Learn

  • Understand the important concepts of OOP in JavaScript, such as scope, objects, inheritance, event delegation, and more
  • Find out how the module design pattern is used in OOP in JavaScript
  • Design and augment modules using both tight augmentation and loose augmentation
  • Extend the capabilities of modules by creating sub-modules using techniques such as cloning and inheritance
  • Move from isolated module pieces to a cohesive, well integrated application modules that can interact and work together without being tightly coupled
  • See how SandBoxing is used to create a medium for all the modules to talk to each other as well as to the core
  • Use the concepts of modular application design to handle dependencies and load modules asynchronously
  • Become familiar with AMD and CommonJS utilities and discover what the future of JavaScript holds for modular programming and architecture

In Detail

Programming in the modular manner is always encouraged for bigger systems—it is easier to achieve scalability with modular programming. Even JavaScript developers are now interested in building programs in a modular pattern. Modules help people who aren't yet familiar with code to find what they are looking for and also makes it easier for programmers to keep things that are related close together.

Designing and implementing applications in a modular manner is highly encouraged and desirable in both simple and enterprise level applications.

This book covers some real-life examples of modules and how we can translate that into our world of programming and application design. After getting an overview of JavaScript object-oriented programming (OOP) concepts and their practical usage, you should be able to write your own object definitions using the module pattern. You will then learn to design and augment modules and will explore the concepts of cloning, inheritance, sub-modules, and code extensibility. You will also learn about SandBoxing, application design, and architecture based on modular design concepts. Become familiar with AMD and CommonJS utilities.

By the end of the book, you will be able to build spectacular modular applications in JavaScript.

Style and approach

This in-depth step-by-step guide will teach you modular programming with JavaScript. Starting from the basics, it will cover advanced modular patterns that can be used in sophisticated JavaScript applications.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 337

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Modular Programming with JavaScript
Credits
About the Author
About the Reviewers
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. What Are Modules and Their Advantages?
Prelude to modular programming
The simple rule for creating modules
A real-life example of modules
A look at a non-modular example
Re-factoring to a more modularized approach
Designing in a modular way
Summary
2. Review of Important JavaScript OOP Concepts
JavaScript objects
Object type constructors
Object literal notation
Function objects
Functions as object constructors (classes)
Functions as static objects
Object literal notation versus function objects
The "this" keyword
Closures
Encapsulation and scoping
Inheritance
Prototype chaining
Property look up in prototype chaining
Resetting the constructor property
Constructor stealing
Parasitic combination inheritance
Constructor property
Native support for inheritance
Summary
3. Module Design Pattern
Module pattern
Internal private scope in module pattern
Adding properties to an interface in module pattern
Object factory module
Creating loose coupling among modules
Application core module
Application Mediator module
Application non-core modules
testModule1 implementation
testModule2 implementation
Auto-initialization of application modules
Module initialization and design considerations
Summary
4. Designing Simple Modules
The big picture
Our application requirements
Dynamic views
Designing our SPA main pieces
Application controller
Application controller modules
Page updater module
Storage handler module
Communication handler module
Utilities module
Message handler module
Logging handler module
Creating our first core module
Structure of our first module
Using our first module's functionality
Mapping our module's methods to its interface
Application view
Creating the index.html page skeleton
Creating an object definition for the header
Generating the Header fragment dynamically
Generating client application's view dynamically
Application model
Creating a module for our application's model
Creating a logging module
Summary
5. Module Augmentation
Principles of module augmentation
Implementing module augmentation
Simple augmentation of ImagesInc_GlobalData
The order of things in module augmentation
Loose augmentation of modules
Loose augmentation of ImagesInc_GlobalData
Testing ImagesInc_GlobalData data encapsulation
Tight augmentation of modules
Tight augmentation of ImagesInc_GlobalData
Loading ImagesInc_GlobalData augmenting code
Considerations in tight augmentation
Generating our application's content area
Summary
6. Cloning, Inheritance, and Submodules
Cloning modules
Creating instances of a constructor function
Using the assignment operator for copying objects
Creating a clone of an object
Shallow cloning and deep cloning
Using external libraries for cloning
Using JSON exploit for cloning
Creating a custom clone method
Creating ImagesInc_Utilites module
Testing our custom cloning method in ImagesInc_Utilites module
An important aspect of our cloning method
Inheritance in modules
Module inheritance using __proto__ object
Module inheritance using parasitic combination
Deciding on the module inheritance approach
Submodules
Adding submodules using dynamic properties
Adding submodules using asynchronous properties
Summary
7. Base, Sandbox, and Core Modules
Application architecture overview
Base module
Adding general-purpose libraries to the base module
Sandbox module
Sandbox module functionality
Sandbox as a consistent interface
Sandbox as a security layer
Sandbox as a communication layer
Sandbox as a filter
Implementing multiple instances of the sandbox module
Advantages of multiple instances of the sandbox
Isolating the sandbox instances from each other
Creating a code execution context
Performance improvements
Core module
Core module construction approach
Core module functionality
Acting as the controller
Providing communication bridges
Initializing and destroying components
Providing plug-and-play capability
Providing a centralized approach to handling errors
Providing application-level extensibility
Leveraging third party libraries
Components
Components required methods
Binding events to the components elements
Component design considerations
Application architectural considerations
Summary
8. Application Implementation – Putting It All Together
The user's view of our application
Application functionality
Index page
Image page
Favorites page
Support widget
Application implementation
Loading our module files in index.html
Base module implementation
Core module implementation
MainCore module implementation
Augmenting MainCore module
Augmenting MainCore using tight augmentation
Augmenting MainCore using sub-modules
Component registration with MainCore
Dynamic loading of components by MainCore
Storing object definitions in local storage
Getting a component's object definition from local storage
Dynamically loading component's resources from the server
Routing functionality in MainCore module
Adding a URL to the history object of the browser
Getting a URL from the history object of the browser
Publish-subscribe implementation in MainCore
Registering components for custom events
Broadcasting custom events by components
SandBox module implementation
SandBox module's constructor
Setting a component's container context in the SandBox instance
Identifying the SandBox module's instance
SandBox module considerations
Application components
Registering components with MainCore module
Header component
Footer component
Content component
Handling content area click events
Handling the Add To Favorite link click event
Handling an image click event
Content area generator methods
NotificationWidget component
NotificationWidget's model
Required methods of the notificationWidget component
Rendering notificationWidget
GlobalData module
Summary
9. Modular Application Design and Testing
Advantages of writing automated tests
Different types of automated tests
Unit testing
TDD unit tests
BDD unit tests
TDD versus BDD
Test coverage
Integration testing
End to end testing
A simple start to writing our unit tests
Writing unit tests without any unit testing frameworks
Adding an AppTester module to our application
Adding unit test suites to our test-runner
CookieHandler module unit tests
Running CookieHandler unit tests
Cleaning up after running our unit tests
Writing unit tests using third party frameworks
Introduction to Jasmine
Setting up Jasmine
Creating our Jasmine spec file
Running our Jasmine unit tests
Exploring Jasmine further
Introduction to Mocha
Setting up Mocha
Chai
Creating our Mocha spec file
Running our Mocha-Chai unit tests
Exploring Mocha further
Summary
10. Enterprise Grade Modular Design, AMD, CommonJS, and ES6 Modules
Revisiting index.html file
Introducing Asynchronous Module Definition
Defining modules using AMD format
Importing AMD modules
Introducing RequireJS
Downloading RequireJS
A test project for creating and loading AMD modules
Creating a simple AMD module
Consuming our person AMD module
Loading dependencies of dependencies
Loading and consuming non-AMD modules
Setting paths in the config object
Creating shims for non-AMD modules
Refactoring Images Inc. application to use AMD format
Modifying Core submodules into AMD modules
Loading our non-AMD modules using RequireJS
Setting up our application's config.js file
Booting up our application using RequireJS
CommonJS
Implementing a CommonJS module
ECMAScript 6 modules
Defining an ES6 module
Consuming an ES6 module
Module loading sequence in the browsers for ES6 modules
Summary
Index

Modular Programming with JavaScript

Modular Programming with JavaScript

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: July 2016

Production reference: 1150716

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-065-0

www.packtpub.com

Credits

Author

Sasan Seydnejad

Reviewers

Joe Dorocak

Muhammad Piracha

Commissioning Editor

Veena Pagare

Acquisition Editor

Smeet Thakkar

Content Development Editor

Mayur Pawanikar

Technical Editor

Anushree Arun Tendulkar

Copy Editor

Safis Editing

Project Coordinator

Nidhi Joshi

Proofreader

Safis Editing

Indexer

Mariammal Chettiyar

Graphics

Disha Haria

Production Coordinator

Nilesh Mohite

Cover Work

Nilesh Mohite

About the Author

Sasan Seydnejad has more than a decade of experience in web UI and frontend application development using JavaScript, CSS, and HTM in .NET and ASP.NET environments. He specializes in modular SPA design and implementation, responsive mobile-friendly user interfaces, AJAX, client architecture, and UX design, using HTML5, CSS3, and their related technologies. He implements framework-less and framework-based applications using Node.js, MongoDB, Express.js, and AngularJS. He is the holder of the U.S. patent for a user interface for a multi-dimensional data store—US Patent 6907428.

Writing this book has been an interesting journey and a lot of work but rewarding at the same time. I would like to thank my family who has always motivated me to learn and progress in my life as well as to help others along the way.

I would also like to thank my friends, my managers, my colleagues and all the other people who have been a positive influence in my life. You have helped me to grow personally and professionally.

Special thanks to my friend Taswar Bhatti for encouraging me to write this book and the book's Content Development Editor, Mayur Pawanikar for keeping me focused on the goal. Also, my book reviewers and all the people in PACKT publishing who made this book possible. My gratitude to JavaScript and open source community as a whole, thank you for your support through out the years.

About the Reviewers

Joe Dorocak, whose Internet moniker is Joe Codeswell, is a very experienced programmer. He enjoys creating readable code that implements the project requirements efficiently and understandably. He considers writing code akin to writing poetry.

Joe prides himself on the ability to communicate clearly and professionally. He considers his code to be a form of communication, not only with the machine platforms upon which it will run, but also with all the human programmers who will read it in the future.

Joe has been employed as a direct employee or a contractor by IBM, HP, GTE/Sprint, and other top-shelf companies. He is presently concentrating on the web app and web project consulting, coding primarily, but not exclusively, in Python and JavaScript. For more details, visit https://www.linkedin.com/in/joedorocak.

Muhammad Piracha is director of engineering at Bamboo Solutions Corporation, based in Reston, Virginia. Bamboo Solutions is a leading provider of software solutions for the Microsoft® SharePoint® platform. Muhammad has over 18 years experience building document management software applications using various Microsoft products.

Currently he oversees several teams across engineering, research and quality assurance to constantly improve the existing portfolio of over 50 products. He is a major driving force in helping the company to develop strategy, architecture, and direction for new initiatives in the SharePoint Online and Office 365™ space.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

There are many JavaScript books on the market these days, and some of them are very good. However, most of them focus on various aspects of the language itself or using certain frameworks to build JavaScript applications. In this book, we are going to take a different approach and look at the architectural design of creating JavaScript applications based on modules, without the need for third-party frameworks.

Creating a good application is more than just writing good code, it is also about how different pieces of the application work and interact with each other. Another characteristic of a good application is its ability to be easily maintained, scaled and extended as needed. A proper modular design enables us to achieve all such goals in our application seamlessly.

In the beginning of this book, I'll be introducing you to the fundamentals of JavaScript modules and the concepts behind a good modular design. Leveraging these concepts, we'll be building an application together, step-by-step, so we can apply what we learn in practice. I recommend reading the chapters in the sequence that they are presented so you can follow along with ease and observe how our design evolves over time.

I would very much encourage you to develop the application pieces with me, as the intent of this book is to be very hands-on, and I would like you to feel as a member of the development team for this application.

As in the real world, we will be re-factoring our code-base a few times during the development phase, in order to implement the new concepts as they are introduced and improve the quality of our application.

Keep in mind that we will be creating a client-side application, and as such, there is no server-side code involved. Nonetheless, many concepts that we will be covering regarding modules and modular architecture can be applied to server-side applications too.

Also, as this book is an introduction to modular JavaScript application design, we will develop a Proof of concept (POC)-grade application together which can provide a good starting point for your own projects.

I have taken a minimalist approach in the implementation, and as a result, we will be using very few third-party libraries in our development process. Therefore, instead of focusing on studying new libraries and how to work with them, you can focus on the application's architecture instead. Once we create a solid foundation, we can incorporate other libraries into our design as required.

For the purposes of clarity, I have shied away from writing fancy code, so you don't have to spend much time trying to understand the intricacies of the code, as opposed to the big picture and how the pieces fit and work together.

Note that this book is meant for people who have a good understanding of JavaScript language, but would like to learn more about JavaScript client-side application design. If you find yourself having trouble with the language itself, you can always refer to online resources and the JavaScript community. This community consists of many smart and helpful people who can, and will be willing to answer your questions. I, for one, am very grateful to the community for its help in my professional growth over the years.

I hope you'll find the book informative and by seeing the benefits of a modular architecture, will use the concepts presented in this book in your own future projects.

What this book covers

Chapter 1, What Are Modules and Their Advantages?, introduces you to the concept of modules and how they can help us design a robust and scalable application.

Chapter 2, Review of Important JavaScript OOP Concepts, covers an overview of some of the important OOP concepts in JavaScript which are necessary for the design and implementation of the modules in our application.

Chapter 3, Module Design Pattern, introduces a very common pattern in creating modules in JavaScript and shows how this pattern can be implemented.

Chapter 4, Designing Simple Modules, uses the module pattern to create simple modules which work together to form the building blocks of our application.

Chapter 5, Module Augmentation, shows the use of various techniques to add more functionality to our modules so that we can extend their capabilities further.

Chapter 6, Cloning, Inheritance, and Submodules, covers how to create modules based on other modules in our application, as well as some more techniques to enhance our modules.

Chapter 7, Base, Sandbox, and Core Modules, introduces some of the main pieces of our application and demonstrates how to create loose coupling among our application modules.

Chapter 8, Application Implementation – Putting It All Together, shows us how to apply all the concepts that we have learned regarding modular architectural design, in order to implement all the pieces of our application.

Chapter 9, Modular Application Design and Testing, covers how to test our application modules using either plain JavaScript or third-party frameworks.

Chapter 10, Enterprise Grade Modular Design, AMD, CommonJS, and ES6 Modules, introduces different modular formats in JavaScript which can be used to design modules, as well as how modules can be imported and exported in our application using these formats.

What you need for this book

You will require any modern browser (IE 9+, Chrome, Safari, Firefox) and any OS that can run a modern browser from the preceding list.

The third-party library required would be jQuery 1.8+.

For the later chapters, the following are the third-party libraries:

Jasmin 2+Mocha (latest version)Chai (latest version)RequireJS (latest version)

Who this book is for

If you are an intermediate to advanced JavaScript developer who has an experience of writing JavaScript code, but probably not in a modular portable manner, or you are looking to develop enterprise-level JavaScript applications, then this book is for you.

A basic understanding of JavaScript concepts such as OOP, prototypal inheritance, and closures is expected.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Notice that I have created a function and called it MyObjDefinition".

A block of code is set as follows:

function doAddition(num1, num2){ return num1 + num2; }

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/ModularProgrammingwithJavaScript. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. What Are Modules and Their Advantages?

In this very first chapter, I will provide you with an overview of the modular design approach in application development as it relates to JavaScript applications.

I will also mention parallels between the modular style of application architecture and the real-life examples of this conceptual design.

Hopefully, as you read along, you'll be able to relate to at least some aspects of the modular design approach and start to see why this style of organizing your code can be extremely beneficial.

The main objective of this chapter is to create a familiar context for you, and to get you started on thinking the modular way as you create and organize your code. Soon, you will see that this approach can organically grow into a well-defined application architecture methodology.

We will start the chapter with a brief discussion on how we can organize our code based on specialization. Then we will look at how we can define modules based on the functionality that they provide.

The topics that are covered in this chapter are:

The simple rule to creating modulesA real life example of modulesA look at a non-modular exampleRe-factoring into a more modular approachDesigning in a modular way

Prelude to modular programming

Many years ago, when I was taking my first computer programming course at college, I found myself having having difficulty organizing my code into functions and classes. I always wondered what kind of criteria I needed to keep in mind to qualify a chunk of code as a function, a class or a subclass. When should I break down one function into multiple functions or a class into multiple classes?

Of course, there were some rules and guidelines that I was familiar with such as: "a function should not be too long or should not do too many things; a class should be a blueprint of a data type" and so on. However, such rules and guidelines seemed abstract to me and I wanted to find a rule that was precise and applicable in all situations.

As I became more knowledgeable in programming concepts and gained more experience in application design, I was able to write more sophisticated code and organize my code better into functions and classes.

However, while my code was organized into well-defined functions and classes, such functions and classes still seemed scattered in different parts of the application. When I needed to make modifications to one piece of the application, I would be concerned about the impact that the change would have on other pieces and the functionality of the application as a whole.

As my applications grew larger and became more complex, the impact of the changes and enhancements became even more pronounced. There were more things things that could adversely affect the application if the application pieces were not designed properly.

Browser-based applications were particularly vulnerable to such impacts as different parts of the application could be manipulating the same element in the browser, which would produce unexpected behaviors and effects in other parts of the application.

On the other hand, making small changes to the application was a challenge on its own, as finding the best place to make such small changes was not always very obvious. Each piece of the application could be performing many different activities from manipulation DOM to writing to cookie to making AJAX calls.

What if I could make one part of the application responsible for only one type of functionality? What if only one part of the application would be responsible for all cookie-related functionality? What if only one piece would make AJAX calls to the server and provide the other pieces of the application with the returned data?

As we design functions and classes to specialize in doing very specific tasks, we can also bundle such functions and classes together to act as a specialized piece of the application responsible for providing one particular functionality. The key point here is to create specialized code packages.

This would mean that changes in how we read and write to cookies would only take place in the package that is responsible for cookie operations and such changes would have no impact on how AJAX calls are made to the server.

If we organize our code into specialized packages, (or modules as we will call them) we can easily achieve this goal of separation of concerns and responsibilities among our application pieces.

But before we can organize our code into modules, we need to see how chunk of code can be considered a module

The simple rule for creating modules

I need to emphasize on the fact that modular programming is not some magical and mystical design concept and pattern that is hard to grasp and even harder to implement. It is really just a practical approach to organizing our code in such a way that each chunk of code only does a very specific and specialized task.

The idea is that each module is a loosely coupled piece of the application, a building block that, along with other pieces (and other modules), creates an ecosystem, that is your application.

So here is the simple rule for creating modules: "If a piece of your application provides a specialized functionality, it can be made into a module that can also be reused in other applications."

I mentioned previously that I was looking for a "precise" rule to help me organize my application code but as my experience has shown, there is no such precise rule other than what I mentioned above, which is in fact not a rule but a guideline. And as a guideline, there is flexibility in what can be considered a module or not. This can be best decided both at the design time and as the application evolves since the application needs can change over time.

A real-life example of modules

Let's consider a familiar modular system. You are most likely reading this book in a place that has electricity and there are many electric outlets in the walls surrounding you. This system enables you to plug in various electrical devices into the outlets and each one of these devices is designed to do a very specific task.

Consider the electrical devices that are plugged into some of these outlets: microwaves, electric kettles, washers, dryers, and so on.

None of these devices care if they are plugged into the electrical outlet in your house or your neighbor's house. They are designed to do their specific task and functionality when they are plugged in and when the power is on, regardless of whose house they are in.

Our application modules should follow the same philosophy. This means, regardless of where in the application they are plugged in and even regardless of what application they are plugged into, they should do their specific task and only their specific task.

Also, in exactly the same way that an electrical device can easily be unplugged from the wall outlet, a code module should be designed in such a way that it can easily be decoupled and removed from your application.

Furthermore, as the removal of one electrical device has no impact on the functionality of other devices that are plugged into your electrical system, the removal of a code module or a series of code modules from your application should not have any effect on the functionality of the other parts of your application.

This decoupling should also have no effect on the application as a whole, other than perhaps just losing the specific functionality that was provided by that particular module or group of modules in your application.

In this book, we will explore how creating modules will help in designing better specialized code pieces that can easily be plugged into and unplugged from our applications. We will also see how modular architecture provides for a more robust and flexible application as a whole.

We will discover how this kind of architectural approach leads to huge advantages in many aspects of our application fundamentals such as code usability, maintainability, testability, and many more.

I hope now you are curious enough to at least consider modular programming in general and JavaScript modular programming in particular as a possible approach for your future application design.

In further chapters, we will apply the same principles that we discussed regarding electrical outlets and appliances to our code modules, in both the design and implementation phases.

Designing in a modular way

In the early stages of designing an application, one of the most important steps is to decide on the functionality that the application needs to provide. This of course, is based on the overall purpose of the application and the type of application that you are designing.

Based on such requirements, in the design phase, you should try to break down the overall functionality (the big picture) of the application into smaller and specialized pieces. Then, you can determine if such pieces already exist, either in the form of third-party libraries or the code that you have already written for a different application.

If you already have your own chunks of reusable code designed in a modular fashion (most third-party libraries are designed in such a way too), it would be much easier and quicker to connect these pieces together and use them in your new application. This would be the same as putting various Lego blocks together to create a play structure.

This type of approach is very important and fits quite well within an Agile development environment. This enables you to work on well defined, specialized modules as you need them and as new application requirements are defined. Also, as you create your code based on modules, you are able to prevent tight coupling among your application pieces.

On the other hand, this approach allows different developers to work on different pieces (modules) of the same application, independently of each other. Another advantage is that modules can be tested separately and in different environments before being added to the application.

In time and with more experience in modular application design and implementation, you will become better at deciding how to distinguish and design your modules. However, it is not realistic to think you can come up with the complete list of all the modules that you could ever need in your application, in the first attempt.

That is because applications evolve and requirements change over time. You may need to create new modules, or modify current ones, or decide to use a different module or library altogether to accommodate such changes in the requirements.

The key advantage of modular design is the flexibility that it provides. Dealing with all the situations mentioned above is a lot easier and requires a lot less effort in a modular architecture. It will also mitigate the impact that adding, removing, or modifying a module could possibly have on the application as a whole.

In the following chapters, you will see how we can create simple and complex modules and how they will be added to our application as loosely coupled pieces.

You will also see how we can load such modules dynamically and on demand when we need them in our application.

So, let's get ready for an exciting journey into our future application design, using modular architecture.

Summary

In this chapter, we tried to get an overview of the concepts behind modular programming in general and how such concepts can be used in JavaScript applications in particular.

We saw that this approach is essentially based on creating packages of specialized code that do very specific tasks.

We also made parallels between how modules are designed in real life and our application modules, so that we can translate the similarities into our own application design approach.

While the term "module" can be used to refer to different things in the code, we will take this terminology to refer to a certain style of programming and architecture in our JavaScript application design approach in later chapters.

However, before we completely dive into the more technical aspects of JavaScript modular programming, it is a good idea to review the fundamentals of object-oriented programming in JavaScript in the next chapter. This will allow us to establish a solid foundation for more technical chapters as we move forward.

Chapter 2. Review of Important JavaScript OOP Concepts

Before we start creating and using our modules in JavaScript, it is important to have a good grasp of important Object Oriented Programming (OOP) concepts in JavaScript. We will rely on such concepts to design and implement our application modules in later chapters.

While my intent in this chapter is not to explore such conceptes in great depth, I will try to provide a good overview of some of the most important related topics.

If you feel that you are quite familiar with these concepts in JavaScript, you could skip this chapter and move on to the next one.

However, if you are not very familiar with OOP in JavaScript, even if you are familiar with similar concepts in classical object oriented languages, I encourage you to follow along as things are a little different in JavaScript. I think it will be worthwhile for you to have a look at these concepts in the realm of JavaScript.

In this chapter, we will cover:

JavaScript objects and their constructorsWhat this keyword is and how it behaves in different contextsClosure and its usesInheritance in JavaScriptPrototype chaining

And other related topics.

JavaScript objects

If you have programmed in JavaScript before (as I'm sure you have, since this book is intended for intermediate to advanced JavaScript programmers), you will certainly have used objects, even if you have not been aware of their inner workings.

If you are familiar with other more classical object oriented languages (such as C++, C#, or Java), you'll be surprised to know that there is no formal syntax for defining classes in JavaScript (at least till ECMAScript 6). I think you'll be