connexo
connexo

Reputation: 56773

Javascript utility function to safely create a namespace

What is the best and most failsafe way to dynamically and safely create namespaces in JS?

I need a utility function for a small utility library I'm working on currently. Basically, I want it to check if any part of my namespace already exists, and is an object, otherwise this part must be initialized and attached as an empty object. Find it here as a jsbin so you can easily fiddle around with it:

http://jsbin.com/leyijojozo/1/edit?js,console

var createNamespace = function (className) {
    var parts = className.split(".");

    var context = window;

    for (var i = 0; i < parts.length; i++) {
        if (!context[parts[i]] || !context[parts[i]] instanceof Object) {
            context[parts[i]] = {};
        }
        context = context[parts[i]];
    }
    return context;
}

This is working fine for namespaces where beforehand no part of the namespace existed before:

createNamespace("A.B.C");
> {}

returns {} (as it is supposed to do), and if I check in console afterwards the namespace fully exists.

But, if any part of the namespace already exists, of course the function should not change it. It works as long as all existing parts are Objects; but it might be possible that one or several parts of the namespace exist, but for example are simple string, Array, Boolean or the like.

Edit: The actual use case which created this question and problem is that I have a site heavyly making use of and . A typical component definition in my application starts like this:

Util.Object.createNamespace("ViewModels.Section.Role").Edit = function (params) { ... }

Amongst many other utility functions (which for example reside in Util.Url, Util.Cookie etc), I have already "namespaced" my Util-library as you can see here, and I like this approach.

I am of course aware that I could simply manually create each part of the namespace, but as a utility function lover ( anyone? :) ) I want a simple function that does it for me in a failsafe way.

Upvotes: 2

Views: 323

Answers (1)

Kristj&#225;n
Kristj&#225;n

Reputation: 18813

A more conservative approach would be to create part of the namespace if (context[parts[i]] === undefined). Then nothing extant can be overwritten, and if you try to push a namespace through a non-object like a boolean, you'll end up with errors.

Upvotes: 1

Related Questions