Last active
July 17, 2016 09:29
-
-
Save monochromer/0171b406adc9bafe40cda982f2649dd2 to your computer and use it in GitHub Desktop.
Создание js-модуля с пространством имен
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
;(function(global, utils) { | |
utils.namespace = function(namespace, closure) { | |
closure.call( | |
null, | |
namespace | |
.split('.') | |
.reduce( | |
function(parent, current, index, keys) { | |
if(!parent.hasOwnProperty(current)) parent[current] = {}; | |
return parent.current; | |
}, | |
global | |
); | |
); | |
}; | |
}(this, (this.utils = this.utils || {})); | |
// usage | |
utils.namespace('foo.bar.baz', function(baz) { | |
// baz is `window.foo.bar.baz` | |
}); | |
utils.namespace('path.to.app', function(app) { | |
// app is `window.path.to.app` | |
}); | |
// | |
function namespace(ns) { | |
var names = ns.split('.'); | |
if (names[0] === 'app') names = names.slice(1); | |
return names.reduce(function(prev, current) { | |
if(!prev.hasOwnProperty(current)) prev[current] = {}; | |
return prev[current]; | |
}, (window.app = window.app || {})); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment