Javascript - Module Pattern

About

The design pattern way to implement a class (object) with the help of the closure capability of the Javascript function.

The module pattern behaves like a class but is a function structure.

The call to a module will instantiate a new function with a new scope.

A modules make possible to hide implementation from the outside world.

Example

function User(name){

    // Private
    var username = name;
    
    // Private
    function returnName() { 
        return username;
    } 
    
    // Public
    var publicAPI = { 
        getName: returnName
    }; 
    
    return publicAPI; 

} 

// User() creates an instance of the User module
var nico = User("Nico"); 
var rixt = User("Rixt"); 
console.log( nico.getName()+" loves "+rixt.getName() );

The new keyword was not used (ie new User()) because User is not a class to be instantiated, User() is just a function.


Powered by ComboStrap