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).

[sourcecode language=”javascript”]

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!!!

}

[/sourcecode]

New code:

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

[sourcecode language=”javascript”]

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’);

[/sourcecode]