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?

29 s
29

I like this:

var yourNamespace = {

    foo: function() {
    },

    bar: function() {
    }
};

...

yourNamespace.foo();

Leave a Comment