Skip to content

Instantly share code, notes, and snippets.

@shrekuu
Last active November 1, 2017 04:19
Show Gist options
  • Save shrekuu/eaaa089758c4eac02192a37a1db37a86 to your computer and use it in GitHub Desktop.
Save shrekuu/eaaa089758c4eac02192a37a1db37a86 to your computer and use it in GitHub Desktop.
ancient js namespace
// Note: these code is tooooo old.
// version 1
function(t) {
function e(t) {
for (var e, i = ("" + t).split("."), r = window, o = 0; e = i[o]; o++) n.call(r, e) || (r[e] = {}), r = r[e];
return r
}
var n = Object.prototype.hasOwnProperty;
t.packager = function(t, n) {
var i = e(t),
r = Array.prototype.slice.call(arguments);
n.apply(i, r.slice(2))
}
}(window)
// version 2
function packager(namespace, factory) {
var parts = namespace.split("."),
parent = {},
part = null;
if (Object.prototype.hasOwnProperty.call(window, parts[0])) {
parent = window[parts[0]];
} else {
window[parts[0]] = parent = {};
}
parts = parts.slice(1);
for (var i = 0; i < parts.length; i++) {
part = parts[i];
if (typeof parent[part] === 'undefined') {
parent[part] = {};
}
parent = parent[part];
}
return parent = factory();
}
// usage:
packager('app.service.users', function() {
var exports = {};
exports.getAll = function() {
console.log('gotcha :P');
}
return exports;
})
// then somewhere else
app.services.users.getAll();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment