DBJ 2008

Somewhat incomprehensible musings on javascript namespaces

by dbjdbj

JavaScript

// (c) DBJ.ORG 2008
// This is how I would like a javascript 'namespace' idiom implemented
// and formalized while using javascript.
// Code is bellow ...

// util function for 2 digit number formating
function F(n, size) {
	var sign = n < 0 ? "-" : "+";
	n = Math.abs(n);
	size = (size == null ? 10 : size);
	return sign + (n < size ? '0' + n : n);
}

function namespace() {
	// scope and visibility of 'counter' are both private to 'namespace'
	var counter = 0;
	// O is object which is nested inside the namespace
	// O, O.m and O.counter all have the public visibility
	this.O = {
		m : function (x) {
			return x + "namespace counter : " + F(counter++) + "\tO counter: " + F(this.counter++);
		},
		counter : -9 // scope of this is 'this.O'
	}
	// please see http://www.crockford.com/ on returning 'this'
	return this;
}
//-------------------------------------------------------------------------------
function TEST(n1, n2) {
	for (var j in[0, 1, 2, 3, 4]) {
		s += n1.O.m("\nn1\t");
		s += n2.O.m("\nn2\t");
	}
}
// usage pattern 1 --------------------------------------------------------------
// n1 and n2 now share the same instance of namespace and also all the instances made inside it !
s = "Shared --------------------------------------------------------------\n\n";
TEST(namespace(), namespace());
// usage pattern 2 -------------------------------------------------------------
// n1 and n2 now DO NOT share the same instance of namespace and also NONE OF instances made inside it !
s += "\n\nUN-Shared --------------------------------------------------------------\n";
TEST(new namespace(), new namespace());
//
document.body.innerText = s ;