Why is this object creation practice used?
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开发者_C百科 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?
In javascript it's possible to use an object before it's declared. This would allow for the !obj
to return false. The author could be protecting against that case. For example
obj = 42
// Lots of code
var obj;
if (!obj) {
// won't get hit
}
It's possible this is a simple misunderstanding of JavaScript and could be deleted. You would need to give us more info about the particular uses to make the call on this. jffriend has an good answer which explains a valid usage of this pattern
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:
JLF.parseColorValue = function (colorStr) {...};
where JLF
is my global library object that keeps everything else out of the global namespace.
That above line of code will only work if JLF
already 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 JLF
in some master file of each project, I include this line at the beginning of each file:
if (!JLF) {var JLF = {};}
So, whichever source file gets included into the project first will create the JLF
object 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:
if (typeof JLF === "undefined") {var JLF = {};}
When there are sub-objects that you want to make sure are declared, you can do that like this:
JLF.config = JLF.config || {};
JLF
must already exist when you do this, but this will make sure that JLF.config
exists.
Perhaps it ensures that if obj exists in the execution context by any chance, before the declaration, this it should be reinitialised before any use, to ensure no conflicts happen at run time.
Or possibly it covers javascript implementations where var doesn't initialise a variable.
精彩评论