Created
May 19, 2009 18:59
-
-
Save furf/114320 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var namespace = function (obj, ns) { | |
var props = ns.split('.'), | |
prop; | |
do { | |
prop = props.shift(); | |
obj = obj[prop] = obj[prop] || {}; | |
} while (props.length > 0); | |
return obj; | |
}; | |
// var foo = {}; | |
// namespace(foo, 'deeply.nested.namespace'); | |
// console.dir(foo); | |
// Simple is better? | |
// Version with optional arguments | |
var namespace = function (ns /*, o, d */) { | |
var o = (arguments.length > 1) ? arguments[1] : window, | |
d = (arguments.length > 2) ? arguments[2] : '.', | |
s = ns.split(d), | |
i, n, p; | |
for (i = 0, n = s.length; i < n; i = i + 1) { | |
p = s[i]; | |
o = o[p] = o[p] || {}; | |
} | |
}; | |
/** | |
* Usage: | |
*/ | |
console.group("var obj = {}; namespace('deeply.nested.foo', obj);"); | |
var obj = {}; | |
namespace('deeply.nested.foo', obj); | |
console.dir(obj); | |
console.groupEnd("var obj = {}; namespace('deeply.nested.foo', obj);"); | |
/** | |
* obj = { | |
* deeply: { | |
* nested: { | |
* foo: {} | |
* } | |
* } | |
* } | |
*/ | |
// Supports multiple namespaces as comma-delimited list | |
var namespaceMulti = function (ns /*, obj, d */) { | |
ns = ns.split(/\s*,\s*/); | |
var obj = (arguments.length > 1) ? arguments[1] : window, | |
d = (arguments.length > 2) ? arguments[2] : '.', | |
j, m, o, s, i, n, p; | |
for (j = 0, m = ns.length; j < m; j = j + 1) { | |
o = obj; | |
s = ns[j].split(d); | |
for (i = 0, n = s.length; i < n; i = i + 1) { | |
p = s[i]; | |
o = o[p] = o[p] || {}; | |
} | |
} | |
}; | |
/** | |
* Usage: | |
*/ | |
console.group("var obj = {}; namespaceMulti('deeply.nested.boo, deeply.nested.foo.bar, deeply.nested.foo.baz', obj);"); | |
var obj = {}; | |
namespaceMulti('deeply.nested.boo, deeply.nested.foo.bar, deeply.nested.foo.baz', obj); | |
console.dir(obj); | |
console.groupEnd("var obj = {}; namespaceMulti('deeply.nested.boo, deeply.nested.foo.bar, deeply.nested.foo.baz', obj);"); | |
/** | |
* obj = { | |
* deeply: { | |
* nested: { | |
* boo: {}, | |
* foo: { | |
* bar: {}, | |
* baz: {}, | |
* } | |
* } | |
* } | |
* } | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment