Tuesday, September 03, 2013

JavaScript Scope and IIFEs

I ran into an issue I've never run into before.  I have some JavaScript files included in most pages on a website. These files define objects and populate them with properties like user options, site root URLs, an ajax callback function, etc...  Well there were a few pages that end up being pop ups on modals, and in that case one of the JavaScript objects wasn't getting created, so I was getting undefined errors.

Initially I created an immediately invoked function on the offending pages that I would pass the object into to make sure it existed and if not populate it.  However you cannot pass a variable or object to an IIF if it isn't defined.  The solution to the problem was simple, but I'd never done this before.  In any function you have access to the window object, which is where all the globals are kept, so you can actually declare global variables in functions without having to declare them outside a function first like I had been doing for years.

 (function () {  
       if (typeof window.SomeObj == 'undefined') {  
        window["SomeObj"] = {};  
        window["SomeObj"].property1 = 'blah blah';  
        window["SomeObj"].property2 = 'some option';  

While I will probably circle back at one point an fix the scripts so that this little hack will not be needed, I thought it was cool you could do this and it had never occurred to me to try it.  Probably not a best practice, and most likely JavaScript 101 to those who develop JavaScript aps, but to me it was new and interesting.  I hope this technique helps someone else as well.


For nested objects, this code snip might be of value as well http://jsfiddle.net/EGZxJ/ which came from http://joonhachu.blogspot.com/ though I haven't tested this yet.