javascript namespace examples

The idea of namespace is to avoid the variable or object name collisions. On a web page, usually there are multiple javascript files. Each of these javascript file will have variables and functions for various tasks. Now, the issue arises when two different javascript files are using the same name for one of the variables or functions. The solution to this is to have wrap all the variables and functions in a javascript file into one namespace, namely one variable/object per javascript file. Here are some ways to namespacing your javascript code.

1. Closure

//closure namespace
var ns1 = {};
(function(){
	this.name = 'namespace 1';
	this.greeting = function() {
		console.log('hello, I am in ' + this.name);
	};
}).apply(ns1);

2. Object literal

//object literal namespace
var ns2 = {
	name: 'namespace 2',
    greeting: function() {
    	console.log('hello, I am in ' + this.name);
    }
};

3. Object

//object namespace
var ns3 = new function() {
	this.name = 'namespace 3';
    this.greeting = function() {
    	console.log('hello, I am in ' + this.name);
    };
};

4. Closure and attach to window

//attach to window directly
(function(ns4) {
    ns4.name = 'namespace 4';
    ns4.greeting = function() {
    	console.log('hello, I am in ' + ns4.name);
    };  
}(window.ns4 = window.ns4 || {}));

To call the greeting function from each of the above namespace

ns1.greeting();
ns2.greeting();
ns3.greeting();
ns4.greeting();

By default, all javascript variables are attached to the window object, thus all of these namespace objects are available from the window object.window.ns1,window.ns2,window.ns3,window.ns4
demo

Search within Codexpedia

Custom Search

Search the entire web

Custom Search