Alternative Module Pattern

Okay, I still havent finished my event package yet, but I do have short article about a variation on the module pattern. I learned this from the conference this Saturday and Douglas Crockfords talk. In my last article I showed the begetObject method; the technique today will user a similar structure.

var myObject = function() {	
	var F = function() {},
		that = null;
	F.prototype = {
		somePublicVariable: true,
		somePublicFunction: function() {
			return that.somePublicVariable;

	that = new F();

	return that;

In this case, inside the Function myObject a new Function F is created. that is initialized to null, but is accessible to all methods inside this closure, including anything you attach to the prototype of F. This is handy because maintaining the scope of the this object can be complex or down-right impossible in certain cases. that will always have the proper scope and anything inside the myObject closure will have access to it. In the past, I have always used an initialization Function to properly set the that (or in previous examples I used self) variable to the newly created object. By using this technique, you do not need to use an initialization Function.

Like other module pattern Functions, this method does not effectively leverage the prototype Object. Each time you call myObject a new memory footprint will be created for Functions and variables attached to the prototype of F, instead of a pointer to the Function defined on the prototype. I believe I will be adopting this technique when writing methods that I previously would have used the old module pattern for: static packages and/or objects initialized once (or just a few times).