What is the proper way to declare a namespace? I've just read "Developing Large Web Applications" and the author suggests using:
if (!window.YourNamespace) {
YourNamespace = {};
}
seems easy enough.. but I see all the javascript libraries for declaring namespaces and alternate methods. Isn't there a standard way to do this? Any problems with the above?
-
It is currently more common practice for javascript developers to use a enclosed module format instead of defining objects on the global scope. Using module loaders such as require.js helps out with this. There are two different module formats to consider: AMD and/or CommonJS, and you can read more about it on the blog post Writing Modular Javascript by Addy Osmani.Spoike– Spoike2013年04月12日 13:07:04 +00:00Commented Apr 12, 2013 at 13:07
7 Answers 7
I've seen this convention used several places.
window.YourNamespace = window.YourNamespace || {};
1 Comment
The mentioned namespace-declarating-way by book author is indeed quite good one. But when you need to repeat it in several files and the namespace has several subnamespaces, it can get quite tedious:
if (!window.Foo) {
Foo = {};
}
if (!window.Foo.Bar) {
Foo.Bar = {};
}
if (!window.Foo.Bar.Baz) {
Foo.Bar.Baz = {};
}
etc...
Instead you should write a simple function that takes care of declaring the namespaces for you:
function namespace(ns) {
var parts = ns.split(/\./);
var obj = window;
for (var i=0; i<parts.length; i++) {
var p = parts[i];
if (!obj[p]) {
obj[p] = {};
}
obj = obj[p];
}
}
Now you can declare the whole nested namespace with just one line:
namespace("Foo.Bar.Baz");
In ExtJS framework this is basically what Ext.ns() function does. I don't really know about other libraries.
Comments
var Utils = {
namespace : function(name) {
return window[name] = window[name] || {};
}
};
or if you prefer your way use:
if (typeof window.YourNamespace === 'undefined') {
YourNamespace = {};
}
3 Comments
There is no standard way as you'll see between frameworks but they do go beyond the basics so that for example X.Y.Z, it will create all objects in that chain if they don't already exist.
Comments
bob.js handles namespaces like this:
bob.ns.setNs('YourNamespace', {
/*define your members here. e.g.:*/
method1: function () { /*...*/ }
});
// now, merge another, sub-namespace.
bob.ns.setNs('YourNamespace.YourSubNamespace', {
method2 function () { /*...*/ }
});
//call methods:
YourNamespace.method1();
YourNamespace.YourSubNamespace.method2();
Comments
Automating namespaces declaration in javascript is very simple as you can see:
var namespace = function(str, root) {
var chunks = str.split('.');
if(!root)
root = window;
var current = root;
for(var i = 0; i < chunks.length; i++) {
if (!current.hasOwnProperty(chunks[i]))
current[chunks[i]] = {};
current = current[chunks[i]];
}
return current;
};
// ----- USAGE ------
namespace('ivar.util.array');
ivar.util.array.foo = 'bar';
alert(ivar.util.array.foo);
namespace('string', ivar.util);
ivar.util.string.foo = 'baz';
alert(ivar.util.string.foo);
Try it out: http://jsfiddle.net/stamat/Kb5xY/ Blog post: http://stamat.wordpress.com/2013/04/12/javascript-elegant-namespace-declaration/
Comments
Some example of namespace function:
namespace = function(ns){
arr = ns.split(".")
parent = window
var temp
while( ( temp = arr.shift()) !== undefined){
parent[temp] = parent[temp] || {}
parent = parent[temp]
}
}
You can then use it as:
namespace("your.own.namespace")
your.own.namespace.Car= function () {
this.speed = 30;
}
1 Comment
Explore related questions
See similar questions with these tags.