Ultimate Library Stub for Javascript

Combining the power of hot buzzwords such as "closures", "private and privileged scoping", "anonymous functions", and "object namespacing", I present a framework for future Javascript libraries.

The code itself

Without further ado, here is the stub:

if(typeof LibStub === 'undefined'){//begin double-include prevention

LibStub = new function()
{
	/*====================*
	 * PUBLIC "CONSTANTS" *
	 *====================*/

	var version = '0.1';

	/*==============*
	 * PRIVATE DATA *
	 *==============*/

	var youCantSeeMe = 3;

	/*=================*
	 * PRIVATE METHODS *
	 *=================*/

	function privateStuff()
	{
		youCantSeeMe = 4;
	};

	/*==========================*
	 * PRIVILEGED METHODS (API) *
	 *==========================*/

	function init()
	{
		privateStuff();
	};

	/*============*
	 * EXPOSE API *
	 *============*/

	//all throwaway public constants
	this.publicData = publicData;
	//all API methods
	this.init = init;
};
}//end double-include prevention

//JQuery to initialize library: $(document).ready(LibStub.init);

You can see it in action with a test harness.

Explanation

The only innovation here is in exposing private methods so they become a privileged API. By keeping the API methods as private variables until the last minute, they are able to refer to each other without the parent object as a prefix or namespace, which can be unwieldy. Learn more about the other techniques:


Comments are closed.