Creating namespaces in JavaScript

In the past it was very common to see global variables in snippets of JavaScript code across the web, such as:

name = "Spock";
function greeting() {
	return "Hello " + name;
}

A better approach is to place all of your code within a namespace; an object that contains all of your code and helps to prevent name clashes with JavaScript code written by others.

The simplest method of creating a namespace is to use an object literal.

var foo = {};
foo.name = "Spock";
foo.greeting = function() {
	return "Hello " + foo.name;
}

This can also be specified using a different syntax.

var foo = {
 
	name: "Spock",
 
	greeting: function() {
		return "Hello " + foo.name;
	}
 
};

This approach is better that having outright global variables, but it exposes everything within the namespace as global. In other words both foo.name and foo.greeting are available everywhere.

Another problem with this approach is that greeting needs to refer to ‘foo.name’ rather than just ‘name’.

Another method of creating a namespace is through the use of a self executing function.

var foo = (function(){
 
	// Create a private variable
	var name = "Spock";
 
	// Create a private function
	var greeting = function() {
		return "Hello " + name;
	};
 
	// Return an object that exposes our greeting function publicly
	return {
		greeting: greeting
	};
 
})();

Here, when the function is executed it creates a private variable and a private inner function. The inner function can refer to the private variable directly. The main function then returns an object literal containing a reference to the greeting private function – this then exposes the greeting function as a public function so we can call it via the foo namespace.

console.log(foo.greeting() === "Hello Spock"); // true

This post was inspired by a good post from David B. Calhoun about spotting outdated JavaScript.

This entry was posted in JavaScript and tagged . Bookmark the permalink. Both comments and trackbacks are currently closed.

3 Comments

  1. Posted December 6, 2011 at 3:20 pm | Permalink

    This article was very helpful!

  2. Phi Le
    Posted January 2, 2012 at 3:40 pm | Permalink

    Thanks for putting this out there, it was easy to understand!

  3. Posted January 8, 2012 at 8:24 am | Permalink

    Nice article!

    I make some improvement to make namespace. The code usage is look like this:

    // before
    function MyClass(){
        this.myMethod = function(){
            alert('Hello world!');
        }
    }
    namespace('my.package1', function(){
        // the same class
        function MyClass(){
            this.myMethod = function(){
                alert('Hello world!');
            }
        }
     
        // turn public MyClass
        return { MyClass: MyClass };
    });

    I put the source code in github:
    https://github.com/fabiooshiro/namespace-js

2 Trackbacks

  1. [...] Essa solução serve para vários arquivos ou trechos de código com namespace. A solução com apenas 1 arquivo JS pode ser como feito no post creating namespace. [...]

  2. By Javascript Scoping 101? « The Pudding Programmer on December 12, 2012 at 6:15 pm

    [...] When your global context is the DOM window, it’s easy to muddy the waters with global variables. Instead, use a method to create a namespace for your program. In this namespace you can create one entry on the window DOM and concisely write and extend your program. There are two or three main ways to do this, but they are best outlined elsewhere. [...]