Javascript Namespaces

More Infos: dustindiaz.com, lixo.org, jeffreysambells.com

var myNameSpace = function NameSpace() {

	// private methods/properties
	var privProp = 'test string';
	function privMethod1(var1) {
		alert('method: privMethod1');
	}
	function privMethod2(var1) {
		alert(privProp);
	}

	// public methods/properties
	return {
		pubMethod1 : function(var1) {
			alert('method: pubMethod1');
		},
		pubMethod2 : function(var2) {
			privMethod1();
		},
		pubVar1 : 'a string'
	}
}();

myNameSpace.pubMethod1();
myNameSpace.pubMethod2();
alert( myNameSpace.pubVar1 );

Anonymus namespace with method export:

(function(){

    function $(id) {
        return document.getElementById(id);
    }

    function test(id) {
        alert($(id).innerHTML);
    }

    window['mytest'] = test;

})();

Tags: ,