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

Posted by Matthew Murdoch on Stack Overflow See other posts from Stack Overflow or by Matthew Murdoch
Published on 2010-02-20T10:57:23Z Indexed on 2010/05/05 16:58 UTC
Read the original article Hit count: 221

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about namespace