module design pattern

JavaScript Module pattern


 

JavaScript module pattern is the one to start, if you are new to JavaScript design patterns. It’s very easy to build a module pattern with a closure and a self-invoking aka IIFE function. This pattern can be written using a normal function or function expression, in this article, we are going to use a function expression. This design pattern will create a private name space, so that the code inside the module will be encapsulated.

Self-invoking function:

Self-invoking function or Immediately Invoked Function Expression (IIFE) is a function which will be executed immediately.

Building the module pattern:

Let’s build a module to count the number of steps walked. The module will take care of increasing the number of steps walked, and it will expose two methods one is to walk() and another one is to getTotalSteps().

  • As mentioned above, let’s build with a self-invoking function expression.

  • let’s add a local variable to hold the number of steps walked.

  • let’s add a private method to increase the number of steps while waking

  • let’s expose the methods to walk and to get the total number of steps.

Exercise.walk(); //will increase the the step + 1

Exercise.getTotalSteps() //will return the total number of steps walked

Complete code:

You may also like

Sponsored

Follow me

Popular posts