jashkenas/underscore — pull request #1373 by diegocard (2013-12-11 04:30:14+00:00)
Title: Add _.namespace

I frequently find myself defining namespaces, so I thought it would be a good idea to implement a utility that does so in a concise, readable and secure way.

From Stoyan Stefanov's book: _"Namespaces help reduce the number of globals required by our programs and at the same time help avoid naming collisions or excesive name prefixing"_.

Some examples of the current implementation are:

```javascript
_.namespace('APP.modules.tests');
// Creates the following structure:
APP = {
modules: {
tests: {
}
}
}
```

Then, you can do the following without erasing the previous namespace:

```javascript
// Preserve the APP.modules.test namespace and add a new one
_.namespace('APP.modules.events').event1 = function() {
// Dependencies can be managed with _.namespace as well
var tests = _.namespace('APP.modules.tests'),
utilities = _.namespace('APP.modules.utilities');

// Function code ...
tests.doSomething();

}
```

By default namespace creation begins from the global object. This is because I assume that the most common use case for namespaces is to avoid global function declaration. However, the parent object can be specified in the following way:

```javascript
function localNamespace() {
var LOCAL_NAMESPACE = {};
_.namespace('modules.local', {parent: LOCAL_NAMESPACE})
// Here I can use LOCAL_NAMESPACE.modules.local
}

// Here LOCAL_NAMESPACE is not defined
```

The default parent element can be changed under _.namespaceSettings.

Finally, I provided a strict mode in case you are worried about typing errors:

```javascript
_.namespace('APP.modules.A');
_.namespace('APP.modules.B', {strict: true}); // Throws an exception because B doesn't exist.
```

Strict mode is disabled by default, but again this can be changed under _.namespaceSettings.

What do you think about this idea? There's always room for improvement, of course.