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 use this approach:
External code can then be:
Sample:
You can optionally declare a
local
variable,same
, likeself
and assignlocal.onTimeout
if you want it to be private.If using a Makefile you can do this.
I prefer to use a Makefile anyway once I get to about 1000 lines because I can effectively comment out large swaths of code by removing a single line in the makefile. It makes it easy to fiddle with stuff. Also, with this technique the namespace only appears once in the prelude so it's easy to change and you don't have to keep repeating it inside the library code.
A shell script for live development in the browser when using a makefile:
Add this as a make task 'go' and you can 'make go' to keep your build updated as you code.
In JavaScript there are no predefined methods to use namespaces. In JavaScript we have to create our own methods to define NameSpaces. Here is a procedure we follow in Oodles technologies.
Register a NameSpace Following is the function to register a name space
To register a Namespace just call the above function with the argument as name space separated by
'.'
(dot). For Example Let your application name is oodles. You can make a namespace by following methodBasically it will create your NameSpaces structure like below in backend:
In the above function you have register a namespace called
"oodles.HomeUtilities"
and"oodles.GlobalUtilities"
. To call these namespaces we make an variable i.e. var$OHU
and var$OGU
.These variables are nothing but an alias to Intializing the namespace. Now, Whenever you declare a function that belong to
HomeUtilities
you will declare it like following:Above is the function name initialization and it is put into an namespace
$OHU
. and to call this function anywhere in the script files. Just use following code.Similarly, with the another NameSpaces.
Hope it helps.
Yes. For example:
then you can have
After porting several of my libraries to different projects, and having to constantly be changing the top level (statically named) namespace, I've switched to using this small (open source) helper function for defining namespaces.
Description of the benefits are at my blog post. You can grab the source code here.
One of the benefits I really like is isolation between modules with respect to load order. You can refer to an external module BEFORE it is loaded. And the object reference you get will be filled in when the code is available.