Wrap your custom JavaScript code in Closure functions

I finally figured out how to use closures properly in JavaScript. This came as a result of my needing to make sure globals I was defining in different script files weren’t conflicting with same named globals in other files. My solution was rather simple, just wrap existing chunks of code in their own function wrapper:

Original Code:
Note that the variables globalVar and anotherGlobal are truly GLOBAL and any other javascript file(s) with the same variables declared will cause major issues for our code (or vise versa).

var globalVar = "";
var anotherGlobal = "";
function init(param1, param2){
	//do work...
	//handle params etc.
	myFunction(); 	//call other functions etc.
}

function myFunction(){
	//do work...
	//can easily reference globalVar and/or anotherGlobal..
	//BUT, so can every other JavaScript function in our site!!!
}

New code:
With everything nice and neatly contained within its own function, where “myLibrary” now becomes the “namespace”.

function myLibrary(param1, param2){
	var globalVar = "";
	var anotherGlobal = "";

	function init(){
		//do work...
		//no longer deal with params, but instead just use them...
		myFunction();	//call other functions etc.
	}

	function myFunction(){
		//do work...
		//can easily work with globalVar and anotherGlobal
		//but they will never conflict with other scripts
		//and other scripts can never access them!
	}

	//only extra step is to call the default "constructor" for the new object
	//this will get called automatically whenever a user calls the main closure function
	init();
}

//then just need to new it up still:
myLibrary('param1','param2');

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s