Javascript - Class like behaviour using module pattern inside an anonymous function

By xngo on March 23, 2019


In Javascript, it is a good practice to wrap your code files within an anonymous function like (function(){ ... })(). The purpose is to namespace your codes and to avoid name collisions.

There are different ways to do this. The codes below will show you how to do it using the Module pattern.

Class like behaviour using Module pattern

The codes are self-explanatory. It shows you how private and public members, and methods are implemented.

var MODULE = (function () {
   function Person(name, age){
        var my = {}; // my is the Person object itself.
        // Private.
        var privateVariable = age;
        function privateMethod() {
            return privateVariable;
        // Public. = name;
        my.moduleMethod = function () {
        my.moduleMethodAccessPrivate = function () {
            return privateMethod();
        return my;
   return {
        // This function allows you to create multiple instance of this module.
        createPerson: function(name, age) {return new Person(name, age);}

Using the module pattern

var john = MODULE.createPerson('john', 22);
var nikki = MODULE.createPerson('nikki', 55);


  • Excellent explanation of Public, Private, Privileged methods by Douglas Crockford
  • JavaScript Module Pattern: In-Depth:
  • Purpose of anonymous function explained:
  • How to set up JavaScript namespace and classes properly?:
  • How anonymous function is executed:
  • Different way to namespace:

About the author

Xuan Ngo is the founder of He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.