Coding Patterns

This page lists some interesting coding patterns that we may or may not use in our code.

Contents

Self Executing Functions

This is already a classic. Using a self calling function declaration to isolate its contents from the current scope, avoiding polluting it with variables.

(function()
{ 
	... 
})();

Objects with Private Stuff

var myObj = function()
{ 
	// Private variables.
	var privateVar = 10;

	var privateFunction = function()
	{ 
        ... 
	};

	// Public stuff.
	return { 
      	publicMethod : function()
		{ 
			// May access privateVar or privateFunction.
        		... 
		}
	};
}();

For Loops and Length

The "length" property should not be checked on each "for" cycle. The following construction should be used instead:

 
for ( var i = 0, len = list.length ; i < len ; i++ } 
{ 
        ... 
} 

Constructors as Pure Functions

On some specific cases, to avoid confusion, there would be some advantage on having "classes" constructors behave like normal functions. To do that:

function FCKeditor( instanceName )
{ 
	if ( this == window )
		return new FCKeditor( instanceName );

	... 
}

So we can use the following calls with the same results:

var editor = new FCKeditor( 'editor' );
var editor = FCKeditor( 'editor' );
This page was last modified on 15 March 2008, at 10:35.