Wednesday 28 September 2016

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




I like this:



var yourNamespace = {

foo: function() {
},

bar: function() {
}
};


...

yourNamespace.foo();

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...