wnas

Javascript coding suggestions

javascript

crockford I am now working on some coding conventions for use at one of my clients. Having done some work on the HTML and CSS ones, I recently started with the javascript one. As I was working on it, I looked at the work done by others, like Douglas Crockford. Some of my co-workers suggested that we did this:

var nameSpace = (function () {
    // declare all of your var's before using them..
	var config, init,x,doStuff;
    config = {
		a : 'a'
	};
	init = function ( arg ) {
		doStuff( arg );
	};
	x = '36';
	doStuff = function ( arg ) {
		// dostuff
	};
	return {
		init:init
	};
}());

While I initially agreed with this, as it seems nice and neat, I spotted a problem with it when it gets big. As you get a really big script and more people working on it, chances are that you will get someone to forget to declare a var in the beginning of the function, hence making it global.
Like this:

var nameSpace = (function () {
	// declare all of your var's before using them..
	var config, init,x,doStuff;
	// we forgot to add doMoreStuff
config = { a : 'a' }; init = function ( arg ) { doStuff( arg ); }; x = '36'; doStuff = function ( arg ) { // dostuff doMoreStuff(); }; // doMoreStuff is global
doMoreStuff = function () { alert( config.b ); };
return { init:init }; }());

So I came up with a (not so revolutionary) way of avoiding this and I am curious what you think of it?
It goes like this:

var nameSpace = (function () {
	// start with var to avoid global variables
	var config = {
		a : 'a',
		b : 'b'
	},
	// continue with a comma to stay in the same var declaration.
		init = function ( arg ) {
		doStuff( arg );
	},
		x = '3',
		doStuff = function ( arg ) {
		// dostuff
	};
	// end with a semi colon.
	return {
		init:init
	};
}());

I think that this has the advantage that when someone else continues with this code he can extend it easily, while not accidentally introducing globlal variables...

var nameSpace = (function () {
	// start with var to avoid global variables
	var config = {
		a : 'a',
		b : 'b'
	},
	// continue with a comma to stay in the same var declaration.
		init = function ( arg ) {
		doStuff( arg );
	},
		x = '3',
		doStuff = function ( arg ) {
		// doStuff
	},
	// if you add a new var it's not global
doMoreStuff = function (){ // do more stuff }
; // end with a semi colon. return { init:init }; }());

What do you think, is this a good way to structure your code or am I missing something?

← Home