What I did at work today

Apr 01 2009

New evolution of my JavaScript pattern

Doesn’t take inheritance into account, but it does a lot of what I want in a basic class.

var Namespace = window.Namespace || {};

Namespace.Foo = function() {
	
	/* --- CONSTANTS --- */
	
	var CONSTANTS = {
		A_CONSTANT_VALUE : 1
	};
	
	// shorthand reference
	var C = CONSTANTS;

	/* --- STATIC VARIABLES --- */
	
	var STATIC = {
		instances : [],
		canBeOverridden : "bar"	
	};
	
	/* --- CONSTRUCTOR --- */
	
	var Instance = function() {
		
	};
	
	/* --- INSTANCE METHODS --- */
	
	Instance.prototype = {
		aPublicInstanceMethod : function() {
			aPrivateMethod(this);
		}
	};
	
	/* --- PUBLIC CLASS METHODS --- */
	
	var publicMethods = {
		initialize : function() {
			var instance = new Instance();
			self.instances.push(instance);
			return instance;
		}		
	};
	
	// combined public methods and static properties so
	// that they're both accessibile anywhere and override-able 
	var self = $.extend(publicMethods, STATIC);
	
	/* --- PRIVATE METHODS --- */
	
	function aPrivateMethod(instance) {
		instance.property = C.A_CONSTANT_VALUE;
	};
	
	// make everything but the private methods accessible,
	// but note that constants will have no effect if overridden
	return $.extend(self, CONSTANTS);
}();

Page 1 of 1