Last active
August 29, 2015 14:01
-
-
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
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 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