2

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.

2
  • I would personally not bother make Java-like or Python-like namespaces in JavaScript, but I landed on this library not so long ago which might do what you want. github.com/mckoss/namespace Or give a look at RequireJS requirejs.org Commented Jun 1, 2015 at 14:59
  • 1
    While both look promising, it also feels like breaking a butterfly on the wheel. I'd be totally comfortable with a small utility function like the one I suggested, but it needs to be made failsafe. Commented Jun 1, 2015 at 15:47

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you more explicitly explain which cases your suggestion has covered that !context[parts[i]] has not?
false, '', and 0, for example, will all evaluate to !context[parts[i]] === true and be replaced with {}. So will null, so you'll have to pick what behavior you want there. None of those are instanceof Object either. I've used === undefined in the past for exactly this case to satisfactory effect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.