Since it is an object literal, it doesn’t need to be instantiated and there is then only one copy of the object. This allows access to all of the methods and attributes from a single global object, as demonstrated below:
Using a singleton for namespacing is quite simple. Once again you can just create an object literal:
As you can see, now if you want to use a utility method, then you can find it somewhere under
Namespace.Util, like what is shown in the next snippet. Of course, as shown by the
some_method function, the methods don’t have to be buried multiple layers into the singleton.
Normally you might just have all of these methods as global functions, which means there is a much higher possibility that they would get overwritten, especially if it a name as simple as
get, which might not be all that uncommon. You could take namespacing one step further and add all of your variables and functions to this singleton to further remove chances of your code being tampered with.
This can be especially useful for adding code for validating different forms that appear on different pages. You can even keep functionality that is used on multiple forms in another part of the namespace, like I did with
Namespace.pageutil.getPageName. This is slightly different than what I was referring to because the
getPageName method isn’t really used by the page-specific code, but is actually used to find the reference to the correct page’s code.
If you thought this was helpful or you just plain liked the article, please spread the word using the social sharing buttons below the post. Small town guys like me don’t get big without the help of users like you. Thanks!