Wanted to get opinions from the experts, I am declaring a variable that will act as the namespace for my application javascript code, but i want to check it is not already defined.
this code is terse and 'seems' to work - any reason I should avoid this and use typeof 'undef' checking instead?
var MY_NAMESPACE = MY_NAMESPACE || {};
Thanks
In the Object Literal Notation, JavaScript namespaces can only be specified once, and only within that namespace may function be written. With a colon between each pair of keys and values, this may be compared to an object with a collection of key-value pairs, where keys can also stand in for new namespaces.
The usual way to declarate variables is const , let and var statements, plus the function and class declaration statements. Contrary, a variable is not defined when it hasn't been declared in the current scope using a declaration statement. The scope sets the limits where the variable is defined and accessible.
Declaring namespaces and namespace membersTypically, you declare a namespace in a header file. If your function implementations are in a separate file, then qualify the function names, as in this example. A namespace can be declared in multiple blocks in a single file, and in multiple files.
JavaScript does not provide namespace by default. However, we can replicate this functionality by making a global object which can contain all functions and variables.
This is the standard way of doing it. See Matt Snider's analysis of the YUI YAHOO.namespace
function which uses this same check (Also for a look at how to make it easy to create namespaces).
Matt's code, which he adapted from YUI to namespace off the window
object instead of the YAHOO
object:
window.object_mes_namespace = function() {
var a = arguments,
o = window,
i = 0,
j = 0,
tok = null,
name = null;
// iterate on the arguments
for (i = 0; i < a.length; i = i + 1) {
tok = a[i].split(".");
// iterate on the object tokens
for (j = 0; j < tok.length; j = j + 1) {
name = tok[j];
o[name] = o[name] || {};
o = o[name];
}
}
return o;
}
Note the o[name] = o[name] || {};
line, which parallels your example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With