Javascript - Module Pattern

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript)

1 - 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.

Advertising

3 - 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.

web/javascript/module_pattern.txt · Last modified: 2019/02/16 17:40 by gerardnico