Alex Rivera | Logout

How should I define a JavaScript 'namespace' to satisfy JSLint?

Asked 2010-02-20T10:57:23.100
21

I want to be able to package my JavaScript code into a 'namespace' to prevent name clashes with other libraries. Since the declaration of a namespace should be a simple piece of code I don't want to depend on any external libraries to provide me with this functionality. I've found various pieces of advice on how to do this simply but none seem to be free of errors when run through JSLint (using 'The Good Parts' options).

As an example, I tried this from Advanced JavaScript (section Namespaces without YUI):

"use strict";
if (typeof(MyNamespace) === 'undefined') {
    MyNamespace = {};
}

Running this through JSLint gives the following errors:

Problem at line 2 character 12: 'MyNamespace' is not defined.
Problem at line 3 character 5: 'MyNamespace' is not defined.
Implied global: MyNamespace 2,3

The 'Implied global' error can be fixed by explicitly declaring MyNamespace...

"use strict";
if (typeof(MyNamespace) === 'undefined') {
    var MyNamespace = {};
}

...and the other two errors can be fixed by declaring the variable outside the if block.

"use strict";
var MyNamespace;
if (typeof(MyNamespace) === 'undefined') {
    MyNamespace = {};
}

So that works, but it seems to me that (since MyNamespace will always be undefined at the point it is checked?) it is equivalent to the much simpler:

"use strict";
var MyNamespace = {};

JSLint is content with this but I'm concerned that I've simplified the code to such an extent that it will no longer function correctly as a namespace. Is this final formulation sensible?

Edit
Report

1 Answer

1

I've encountered this issue before. You definitely don't want to use your final form, as it is completely bypassing the check for a defined variable and will always overwrite it to an empty object, even if things were already stored in it.

I think your second to last form is the most appropriate for creating a namespace, but really the first form is decent as well. The errors that JSLint reports with it are sort of catch-22s in my opinion and not much to worry about. The reason I think it's not a big deal to leave off the declaration is that, in the case where the namespace is loaded at some previous point, you'd end up with JSLint's "variable was used before it was defined" error, so you're essentially just trading one warning for another.

answered 2010-02-20T11:14:00.467

Your Answer