Skip to content

Instantly share code, notes, and snippets.

@yckart
Forked from 140bytes/LICENSE.txt
Last active December 21, 2015 23:39
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 yckart/6384176 to your computer and use it in GitHub Desktop.
Save yckart/6384176 to your computer and use it in GitHub Desktop.
Namespacer
function (
a, // the namespace-string
b, // something what could populate the last key (optional)
c, // the object you want to use as namespace-object (optional)
d // token-placeholder
) {
a = a.split('.'); // split the namespace e.g.: 'foo.bar.foz.baz' => ['foo', 'bar', 'foz', 'baz']
c = c || this; // the namespace object (window per default)
while (d = a.shift()) // iterate over the splitted namespace and store it in `d`
c = (c[d] = (a[0] ? c[d] : b) || {});
return c;
};
function(a,b,c,d){a=a.split('.');c=c||this;while(d=a.shift())c=(c[d]=(a[0]?c[d]:b)||{});return c}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 Yannick Albert <http://yckart.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "Namespacer",
"description": "A simple library for creating namespaces in the browser.",
"keywords": [
"namespace",
"string",
"object"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>140byt.es</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var ns = function(a,b,c,d){a=a.split('.');c=c||this;while(d=a.shift())c=(c[d]=(a[0]?c[d]:b)||{});return c};
ns('foo.bar.foz.baz', function () {
return '140byt.es';
});
document.getElementById( "ret" ).innerHTML = foo.bar.foz.baz()
</script>
@atk
Copy link

atk commented Aug 30, 2013

A little smaller:

function(a,b,c,d,e){d=c=this;a.replace(/\w+/g,function(f){e=e||f;d=d[f]={}});d=b;return c[e]}

@yckart
Copy link
Author

yckart commented Aug 30, 2013

@atk Your code above doesn't populate the object with what is passed as the second argument...

typeof foo.bar.foz.baz !== 'function'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment