Skip to content

Instantly share code, notes, and snippets.

@jherax
Created May 26, 2015 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jherax/97cce1801527b84782a2 to your computer and use it in GitHub Desktop.
Save jherax/97cce1801527b84782a2 to your computer and use it in GitHub Desktop.
JavaScript: Crear namespaces
//utility to create safe namespaces
function createNS (namespace) {
var nsparts = namespace.toString().split("."),
reName = (/^[A-Za-z_]\w+/),
cparent = window,
i, subns, nspartsLength;
// we want to be able to include or exclude the root namespace so we strip it if it's in the namespace
if (nsparts[0] === "window") nsparts = nsparts.slice(1);
// loop through the parts and create a nested namespace if necessary
for (i = 0, nspartsLength = nsparts.length; i < nspartsLength; i += 1) {
subns = nsparts[i];
// check if the namespace is a valid variable name
if (!reName.test(subns)) throw new Error("Incorrect namespace");
// check if the current parent already has the namespace declared,
// if it isn't, then create it
if (typeof cparent[subns] === "undefined") {
cparent[subns] = {};
}
cparent = cparent[subns];
}
i = subns = nsparts = nspartsLength = reName = void(0);
// the parent is now constructed with empty namespaces and can be used.
// we return the outermost namespace
return cparent;
}
// WAY 1: we can create the structure with local references
(function () {
// If you use local/cached references is recommended declare them
// within a function or module at the top of your function scope;
// this is called: Dependency declaration pattern
var _2d = createNS("animation.g2D"),
_3d = createNS("animation.g3D");
// you can get the reference of created namespaces
_2d.slide = function() {};
_3d.cubic = function() {};
}());
// WAY 2: passing the object reference as a proxy
(function (proxy2D) {
proxy2D.slide = function() {};
})(createNS("animation.g2D"));
(function (proxy3D) {
proxy3D.cubic = function() {};
})(createNS("animation.g3D"));
// WAY 3...n, you can use Module Pattern: loose augmentation, etc...
@jherax
Copy link
Author

jherax commented May 26, 2015

Esta función esta implementada en la librería JSU

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