Skip to content

Instantly share code, notes, and snippets.

@monochromer
Last active July 17, 2016 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monochromer/0171b406adc9bafe40cda982f2649dd2 to your computer and use it in GitHub Desktop.
Save monochromer/0171b406adc9bafe40cda982f2649dd2 to your computer and use it in GitHub Desktop.
Создание js-модуля с пространством имен
;(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