JavaScript Notes: Namespaces (er, objects)

Simple Hacks

Here's some JavaScript code sitting in the global namespace. It will work until you write some additional code where you accidentally reuse a variable name or redefine a function. It will definitely break if you include someone else's code with the same name clashes. This is called "polluting the global namespace" 

//-----------------------------------
//	traditional JavaScript
//-----------------------------------
//
var counter=42;
//
yada1 = function(txt){
	counter+=1;
	console.log(txt+" "+counter)
}
yada2 = function(){
    for (i=0;i<2;i++){
	yada1("test");
    }
}
yada2();	// this will work
yada1 = 99;	// this is legal but wrong
yada2();	// this will fail (TypeError: yada1 is not a function)

Here are three examples where the JS code above has been moved into three different objects that will be used to implement JS namespaces. Hit your F12 key then select the console tab to see the output.

//-----------------------------------
//	demo_001.js
//-----------------------------------
//
console.log("-i-starting demo_001.js")
var counter=42;	// this global variable must never change
//
//-----------------------------------
//	objects as namespaces
//-----------------------------------
console.log("creating 3 name spaces");
//
//	ns demo #1 (direct assignment - simple)
//
var nsNSR1 = {}
nsNSR1.counter=10;
nsNSR1.yada = function(txt){
	nsNSR1.counter+=1;
	console.log(txt+" "+nsNSR1.counter)
}
//
//	ns demo #2 (direct assignment - better)
//
var nsNSR2 = {}
nsNSR2.counter=20;
nsNSR2.yada = function(txt){
	this.counter+=1;
	console.log(txt+" "+this.counter)
}
//
//	ns demo #3 (object literal notation - best)
//
var nsNSR3 = {
	counter: 30,
	yada: function(txt){
		this.counter+=1;
		console.log(txt+" "+this.counter);
	}
}
//-----------------------------------
//	testing
//-----------------------------------
console.log("-i-now testing")
//
for (i=0;i<2;i++){
	nsNSR1.yada("nsNSR1");
}
for (i=0;i<2;i++){
	nsNSR2.yada("nsNSR2");
}
for (i=0;i<2;i++){
	nsNSR3.yada("nsNSR3");
}
if (counter==42){
	console.log("-i-global variable 'counter' is still 42")
}else{
	console.log("-e-global variable 'counter' changed")
}

Back to Home
Neil Rieck
Waterloo, Ontario, Canada.