How to create a javascript global library (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:

  • Global library
  • Global module.

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:

  • A minimal library
let myLibrary = {
   "hello": function(to) {
       if(to===undefined){
          to = this.user;
       }
       console.log(`Hello ${to} !`); 
   },
   "user":"Anonym"
}
  • Usage:
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:

  • public if you add it to the global variable
  • private otherwise (ie they stay in the scope of the IIFE function)

Example

window.libraryName = window.libraryName || {};
  • The library definition that:
    • is done inside a IIFE in order to scope the variable.
    • gets the global variable as argument.
(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 || {} );
  • Usage:
libraryName.hello();
libraryName.hello("You");
libraryName.greeting = "Hoi";
libraryName.hello("You");
  • Result:

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 || {}) );
  • When we use it, the Hello greeting from the first library definition is used.
libraryName.highFiveHello();
libraryName.highFiveHello("You");
  • Result:

Library using this pattern

The below library uses the following global variable

  • jQuery or $ for Jquery
  • _ for lodash





Discover More
Javascript - Immediately invoked function expression (IIFE)

An IIFE (pronounced “iffy”) is a function expression that is immediately invoked in order to create a local scope for the variables They therefore won’t affect the surrounding code outside of it...
Javascript - Library

library in Javascript. A library is a distribution format as a package that is created from a module bundle from a prototype The difference between a package and a library is that the modules are...
Javascript - Module

functionality in Javascript. A module is different from a script file because: it defines a well-scoped object that does not pollute the global namespace. It list explicitly its dependencies Javascript...
Javascript - Module Pattern

This article shows classic design pattern with ECMAScript on how to organize javascript code with a structure that make possible to: get input return output and hide the implementation from the...
Javascript - Universal Module Definition (UMD)

The UMD module format try to be the glue between differents modules definition by offering template A UMD module wraps the following module format: a Global Variable module the CommonJS format...
WebPack - Dependency

in WebPack To exclude a package with webpack, you have to: declare it as peerDependency) to define its corresponding global Example with JQuery that is available on the global variable...



Share this page:
Follow us:
Task Runner