Add multiple entities to Javascript namespace from different files
- by Brian M. Hunt
Given a namespaces ns used in two different files:
abc.js
ns = ns || (function () {
foo = function() { ... };
return {
abc : foo
};
}());
def.js
// is this correct?
ns = ns || {}
ns.def = ns.def || (function () {
defoo = function () { ... };
return {
deFoo: defoo
};
}());
Is this the proper way to add def to the ns to a namespace? In other words, how does one merge two contributions to a namespace in javascript?
If abc.js comes before def.js I'd expect this to work. If def.js comes before abc.js I'd expect ns.abc to not exist because ns is defined at the time.
It seems there ought to be a design pattern to eliminate any uncertainty of doing inclusions with the javascript namespace pattern.
I'd appreciate thoughts and input on how best to go about this sort of 'inclusion'.
Thanks for reading.
Brian