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?
I like this:
I use the following syntax for the namespace.
jsfiddle: http://jsfiddle.net/rpaul/4dngxwb3/1/
I've written another namespacing library that works a bit more like packages / units do in other languages. It allows you to create a package of JavaScript code and the reference that package from other code:
File hello.js
File Example.js
Only the second file needs to be included in the page. Its dependencies (file hello.js in this example) will automatically be loaded and the objects exported from those dependencies will be used to populate the arguments of the callback function.
You can find the related project in Packages JS.
Another way to do it, which I consider it to be a little bit less restrictive than the object literal form, is this:
The above is pretty much like the module pattern and whether you like it or not, it allows you to expose all your functions as public, while avoiding the rigid structure of an object literal.
If you need the private scope:
else if you won't ever use the private scope:
My habit is to use function myName() as property storage, and then var myName as "method" holder...
Whether this is legitimate enough or not, beat me! I am relying on my PHP logic all the time, and things simply work. :D
if (this !== that) myObj.fName1(); else myObj.fName2();
Reference to this: JavaScript: Creating Object with Object.create()