Skip to content

Instantly share code, notes, and snippets.

@cjwainwright
Last active August 29, 2015 14:01
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 cjwainwright/f5a368a4fe2e20bef899 to your computer and use it in GitHub Desktop.
Save cjwainwright/f5a368a4fe2e20bef899 to your computer and use it in GitHub Desktop.
Using ES6 Proxies to create a namespace root allowing automatically created child namespaces via a get trap
function ns(x) {
return new Proxy(x, {
get: function(target, name) {
if(target.hasOwnProperty(name)) {
return target[name];
}
return target[name] = ns({});
}
});
}
ns = ns(ns); // reuse the global function ns as a root namespace
// usage examples
ns.utils.extend = function () {}; // no need to define 'utils' first, it is automatically created
ns.dom.components.Graph = (function () { })(); // likewise, 'dom' and 'components' namespaces are automatically created
ns.should.I.not.be.using.amd.instead = 'probably'; // you get the idea
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment