Last active
December 16, 2015 03:39
-
-
Save stamat/5371124 to your computer and use it in GitHub Desktop.
JavaScript namespace declaration
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(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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment