var obj;
if (!obj) obj = {};
obj.foo = {};
// ...
I see this in the beginning of source code all the time. I don’t understand why someone would want to resort to such an unnecessary approach to creating an object. As per the if statement, of course it’s going to evaluate to true because obj is undefined. So why do people want to create their objects this way? Is there so sort of benefit I don’t know about?
This is a common practice when using an object to help manage the global namespace. For example, in my code, I have a set of global functions spread across a whole bunch of source files. They are grouped into files according to functionality and, in any given project, I may only include use some of the files. So, each file needs to stand alone.
Yet, all the functions are declared like this:
where
JLFis my global library object that keeps everything else out of the global namespace.That above line of code will only work if
JLFalready exists as an object so the parseColorValue function can be added to it as a property.So, in order to make each of these files independent of all the others and not have to worry about pre-declaring
JLFin some master file of each project, I include this line at the beginning of each file:So, whichever source file gets included into the project first will create the
JLFobject and all other source files will use the previous declaration and not create another one or assign over the top of the previous one.FYI, I’ve also see it done this way:
When there are sub-objects that you want to make sure are declared, you can do that like this:
JLFmust already exist when you do this, but this will make sure thatJLF.configexists.