Table of Contents

Javascript - How to create a javascript global library (with the namespace pattern)

About

namespace pattern is when libraries made themselves available from everywhere using a single global variable

From everywhere, means that:

They are also known as:

Basically, a library is just a object stored in a global variable but you can add scope functionality thanks to function. The below steps show you step by step how a library is build and even how plugin can be added.

Steps

Basic: Object

The basic implementation of a globale namespace pattern is to use directly an object as global variable

Example:

let myLibrary = {
   "hello": function(to) {
       if(to===undefined){
          to = this.user;
       }
       console.log(`Hello ${to} !`); 
   },
   "user":"Anonym"
}
myLibrary.hello();
myLibrary.hello("World");

There is no private variable sharing possible between the function in this construct. This is why the below function construct is more often used because it adds a scope.

With scope: IIFE Function

In this global namespace pattern:

The scope of the variable or function is:

Example

window.libraryName = window.libraryName || {};
(function( globalVariable ) {
   
    // Public Property because created on the global variable
    globalVariable.greeting = "Hello"; 
    
    // Private Property (scoped to stay inside the IIFE)
    let defaultName= "Anonym";

    // Public Method  because attached on the global variable
    globalVariable.hello = function( to ) {
        helloWorld(to);
    };

    // Private Method
    function helloWorld( to ) {
        if (to===undefined ){
          to = defaultName;
        }
       console.log( `${globalVariable.greeting} ${to.trim()} !`);
    }
})( window.libraryName = window.libraryName || {} );
libraryName.hello();
libraryName.hello("You");
libraryName.greeting = "Hoi";
libraryName.hello("You");

With Plugin

Note that passing the below argument construction to the IIFE permits to build up the library (global variable) by applying several IIFE to the global variable (ie library)

window.libraryName = window.libraryName || {}

This is the basis for plugin building.

Example:

(function( globalVariable ) {
   
    globalVariable.highFiveHello = function( to ) {
       if (to===undefined ){
          to = "Anonym High Five";
          // Using
          // to = defaultName; 
          // will not work because the `defaultName` variable was private.
        }
        console.log( `${globalVariable.greeting} ${to.trim()} \u270B! `);
    };

}( window.libraryName = window.libraryName || {}) );
libraryName.highFiveHello();
libraryName.highFiveHello("You");

Library using this pattern

The below library uses the following global variable