I've been told namespaces shouldn't be used, as they 'pollute' the global scope. I wonder what are the alternatives?
When I want to define utility functions and / or constants e.g. for a website, a simple way to go would be to define them by namespaces, that way the damage to the global scope is restricted to one object only.
If namespaces are bad practice, a couple of questions comes to mind:
This question is a result of a discussion started on a post on the benefits of using extend.js.
why is this bad practice?
namespaces themself are bad because it's an unnecessary concept.
Having objects with properties and methods is acceptable. It's also fine to have a "module" token which is similar to a "namespace" but instead the meaning is that you have one "module" token per file which contains all your properties and methods. This is different from a "namespace" because it's only created / altered in a single file and isn't exposed as a global token.
what's the scope of this declaration (web applications / dynamic websites / static websites etc.)?
All ECMAScript, never create new global tokens
what are the alternatives?
Rather then having namespaces you should favour multiple "file local" tokens. Meaning that each file / "module" should be wrapped in a closure and you should have access to multiple local variables inside this closure.
Global variables are also bad because you don't need them, at all, ever. The way you avoid globals is by wrapping everything in closures and being intelligent in how you load external javascript files.
Examples of zero global module loaders
Further reading:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With