trustyfrog trustyfrog - 4 years ago 145
Javascript Question

How do I declare a namespace in JavaScript?

How do I create a namespace in JavaScript so that my objects and functions aren't overwritten by other same-named objects and functions? I've used the following:

if (Foo == null || typeof(Foo) != "object") { var Foo = new Object();}


Is there a more elegant or succinct way of doing this?

Answer Source

I like this:

var yourNamespace = {

    foo: function() {
    },

    bar: function() {
    }
};

...

yourNamespace.foo();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download