Just to present a different perspective. You can write code without using closures and maintain a (possibly) safe area of โโthe global variable.
Define one object to use as a namespace with a suitable unique name (for example, MyAppContext) that will have a global scope, and if you need to define global variables for use only in your application, attach them to this object.
MyAppContext.apptitle = 'Application Name';
At the beginning of your script where you create MyAppContect
, make sure it does not exist.
Make sure that all variables with a functional range use the var
keyword, so you know that you are not referencing a global value.
Obviously, this approach poses a risk that you forget to define some of your function variables with var
. JSLint can help you with this.
I am happy to cancel this answer if I start to cry, but I believe that this is an acceptable alternative approach to using closures. And hey! this is an old skool
I also agree that using closures is safer, but thought it might interest you.
source share