Created
May 26, 2015 04:00
-
-
Save jherax/97cce1801527b84782a2 to your computer and use it in GitHub Desktop.
JavaScript: Crear namespaces
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
//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; | |
} |
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
// 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... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Esta función esta implementada en la librería JSU