Book Image

Modular Programming with JavaScript

Book Image

Modular Programming with JavaScript

Overview of this book

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.
Table of Contents (17 chapters)
Modular Programming with JavaScript
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
2
Review of Important JavaScript OOP Concepts
Index

Introducing Asynchronous Module Definition


Asynchronous Module Definition (AMD) format for creating modules in JavaScript, is targeted for use in browsers. This format proposes a particular way for defining modules so that modules and their dependencies can be loaded into the browser asynchronously.

There are two key methods that you need to use when creating and consuming AMD modules, these are define and require methods.

The idea is that we create a module using the global define method and then we can import that module in other parts of the code (other modules) using the global require method.

Defining modules using AMD format

Here is how a module can be defined in AMD format:

define('moduleOneId', ['dependency'], function(dependency) {

    return {
        sayHi: function(){
            console.log('Hi there!')
        }
    }
});

In the preceding code, we are passing three arguments to the global define method, which has been provided to us by an AMD-compatible module loader.

The first...