Javascript module pattern with constructor with arguments

Javascript module pattern

As Douglas Crockford wrote on Javascript: the good parts, a module is a function or object that presents an interface but hides its state and implementation.

I used indeed the module pattern once I needed encapsulation, i.e. to have a class method that had a public interface but that hid implementation details.

In addition to encapsulation I needed a costructor with arguments, so I added it too in the following code, which implements the module pattern with a constructor.

The constructor is defined as it is usually done in Javascript.

The module pattern has been used in the prototype implementation, where we have

  • privateFun which is a private method, visible only from publicFun
  • publicFun which is a public method, externally visible
  • the return which returns an object whose members are externally visible, and so where we put public method

We have used in the code:

  • immediately invoked function expressions
  • closures

Immediately invoked function expressions

IIFE (immediately invoked function expressions), like

make so that the function is immediately executed, and that the result is returned with the return we talked about above


Closures allow functions defined in a certain scope to continue to have access to the variables declared in that scope even when the outer function which defined that scope has terminated. In the example above we see how we access the variable i even when the outer function has ended its life cycle.