JavaScript Namespacing

Introduction

Namespace is the term given to a mechanism for protecting against name collision. When developing a set of functions, variables or other forms of definition, it is virtually impossible to conjure unique names. When placed in the same context as another similar set of definitions there is always the potential for two developers to have used the same name. Such duplication makes it difficult for the system to identify which definition to use, which is known as a name collision or name conflict.

Namespaces have a formal definition in Java (packages) and XML (https://www.w3.org/TR/xml-names/) but not in JavaScript. Java packages also provide scope control that ensures data and functions can be kept private and specific interfaces exposed. Although independent of XML Schemas (XSD), XML Namespaces can be associated to enable controlled definition of the XML structure.

ECMAScript 6 (ES2015) will introduce module loading that will facilitate both name collision avoidance and scope control, but until ES2015 is widely supported by web browsers an alternative approach is required. This article describes an approach that uses pure JavaScript.

Readers more familiar with common design patterns might recognise this namespace implementation as an application of the Factory design pattern (aka Function Factory). The Function Factory (FF) is an alternative approach to attempting to simulate classical OO in JavaScript (pre-ECMAScript 6). Slightly off topic but: FF is a fine OO trade-off between speed of object instantiation (JS classes are twice as quick but only noticeable when generating 10’s of thousands of objects, which is probably not a good idea within a web browser anyway) verses syntax and scope complications (the keyword ‘this’ becomes unreliable with JS classes. FF also has the advantage of true private content thanks to closures.)

The examples given in this article can be found in my GitHub repo.

Construction

To develop our JavaScript Namespace we will employ three techniques; closures, anonymous (aka lambda) functions and immediately invoked function expressions (IIFE). These techniques are slightly advanced JavaScript but ease to master so this section will describe each in turn.

Closures

A closure in most programming languages relates to a construct that maintains its own scope. In JavaScript (JS) this goes a little further in that we also have to maintain persistence to facilitate private data and functions. Again JS does not have a formal construct but is defined using two considerations:

  1. Define a function within a function
  2. Return a reference to the inner function by the outer function.
function outer() {
  var message = ‘hello world’;

  function inner() {
    alert(message);
  }

  return inner;
}

var helloClosure = outer();

In the example above a call to helloClosure() will result in the inner function being called and display of the message ‘hello world’. The reference to the inner function can be included in an object, returned by the outer function, to expose (make public) a select group of inner functions; leaving the unexposed functions and variables private within the closure.

Anonymous functions

Also known as lambda functions (from the functional programming stable), anonymous functions are, as the name suggests, functions without a name. JavaScript supports first-order functions which means they can be treated like any other data. The can be returned form a function, as demonstrated above, and assigned to a variable.

var reference = function() {
  // anonymous, nameless or
  //  lambda function.
};

var named = function onymous() {
  // named function.
};

The above example shows two variables ‘reference and named’ being assigned a value that happens to be a function; not the result of the function but the function body itself. However, the function assigned to ‘reference’ does not have a name so,

console.log( named.name!== ‘’);
console.log( reference.name=== ‘’);

both return true but both are value. Anonymous functions are very often used for callbacks and event handlers when the function only has one purpose and does not need to be call from anywhere else; exactly the case when defining a namespace.

Immediately Invoked Function Expression (IIFE)

According to the cyber-font-of-all-knowledge that is Wikipedia, this feature is pronounced ‘iffy’, which makes them sound like they cannot be trusted; not true. Again in the situation when you have a function with only a single purpose, IIFE perform their task (and possible return a result) potentially never to be called again. Often IIFE are anonymous so their definition is destroyed after execution (unless it is a closure), and the global scope kept clean.

var iify= (
  function() {
    return ‘hello world’;
  }
)();

In the example above a variable ‘iffy’ is assigned the result of an anonymous function ‘hello world’; the definition of which will subsequently be destroyed.

Bring it all together

In our namespace we want to protect public functions from collision whilst also keeping private data and functions that do not need exposing. We first declare an anonymous closure to contain all our data and functions, returning an object (interface) to expose only those functions we want to make public.

var definition=
  function() {
    var privateData = 
      ‘HELLO WORLD’;

    function privateFunction() {
      return privateData;
    }

    function publicFunction() {
      return privateFunction().
        toLowerCase();
    }

    return {
      getData: publicFunction
    };
  };

Whilst the function remains anonymous it is assigned to the ‘definition’ variable, which enables us to bring the namespace into existence by calling the declaration function.

var namespace = definition();

Thus a call to namespace.getData will yield the text ‘hello world’ in lowercase. The privateData and privateFunction components remain hidden outside the closure; but be can do better.

One problem with the above solution is we could use the definition function more than once but we have no such requirement. By making the definition ‘iffy’ we can define the namespace and declare it at the same time.

var namespace= (
  function() {
    var privateData = 
      'HELLO WORLD’;

    function privateFunction() {
      return privateData;
    }

    function publicFunction() {
      return privateFunction().
        toLowerCase();
    }

    return {
      getData: publicFunction
    };
  }
)();

This will drop the reference to the closure (outer function), making it (virtually) impossible to re-declare the namespace, whilst retaining the interface (object with references to the inner functions.)

The following code will result in the execution of the publicly exposed function using the getData method of the namespace interface, using either of the solutions for declaring the namespace described above.

alert( namespace.getData());

Putting it in practice

So you have some functions you have designed, developed and tested but you need to make them live. However, you know there will be other functions in the code base and you want to protect yours from potential name collision – so we use a Namespace. Here is our skeleton namespace.

var namespace= ( 
  //  We can give the namespace a useful name.
  function() {
    //  We can have parameters if required 
    //    to initialise the namespace.
    //  Private data in here
    //  All functions (public and private) 
    //    defined here.

    return {
      // Expose the functions we want to make public 
      //  but assigning the an interface.

      //  interface: function-name,
      
      //  They can be the same name but better if not.
    };
  }
)(); //  Here is where we supply the namespace 
//  with actual parameters, if required.

All we need to do is read through the comments and replace them with our existing code (where applicable), ensuring the calls to our functions are prefixed with the namespace. The calls will also have to apply the interface names for the public functions, if different from the implementation. As a rule we should not be referencing any resources outside the namespace from within, but should have references passed in as parameters of the namespace (function).

Here is a scenario: we have a set of functions that issue calls to a database to administrate a list of users:

  • createUser( userName, password, fullName)
  • getUserDetails( userName)
  • changePassword( userName, oldPwd, newPwd)
  • disableUser( userName, adminPwd)

We create a namespace called userAdmin as follows:

var userAdmin= (
  function(strDB_ConnectionString) {
    //  We have no private data as present.

    function createUser( userName, password, fullName) {
      //  Original function.
    }
//  :  Copy all the original functions here but 
//       change the reference to database connection 
//       string to StrDB_ConnectionString.

//  We can extract common code in here to re-use but 
//    keep hidden from outside the namespace

    return {  //  Public interface
      //  Public/Interface name : 
      //    Private/Implementation name[,]

      newUser: createUser,
      readUser: getUserDetails,
      updatePwd: changePassword,
      deleteUser: disableUser
    };
  }
)(
  //  Original DB connection string here.
);

Now, instead of calling:

changePassword()

we call:

userAdmin.newUser()

The only potential name collision we have to concern ourselves with now in the name of the namespace itself, everything inside is protected.

Summary

Namespaces are a common technique for ensuring your definitions avoid colliding with those of another domain. Many implementations bring added benefits like hiding private data/functions or schema-based validation. Whilst most JavaScript engines currently (Feb 2016) do not support the standardised approach (Modules in ES6) there is a way of achieving the same level of protection using pure JavaScript through combining a Closure, an Anonymous function and Immediately Invoked Function Expression (IIFE), that works very effectively.