Skip to content

Instantly share code, notes, and snippets.

@jalcine
Created October 25, 2012 16:55
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 jalcine/3954021 to your computer and use it in GitHub Desktop.
Save jalcine/3954021 to your computer and use it in GitHub Desktop.
Implementing Namespaces in CoffeeScript and JavaScript
# Define the global namespace as 'root'.
root = module?.parent?.exports ? window
###
@fn namespace
Allows you to implement a namespace of objects to the global namespace.
###
root.namespace = ->
separator = "."
base = root
for own key, value of arguments[0]
components = key.split separator
if components.length isnt 1
for component in components
if !base[component]
base[component] = {}
base = base[component]
else
base[key] = {}
base = base[key]
for own propertyName, propertyValue of value
base[propertyName] = propertyValue
base
var root, _ref, _ref1,
__hasProp = {}.hasOwnProperty;
root = (_ref = typeof module !== "undefined" && module !== null ? (_ref1 = module.parent) != null ? _ref1.exports : void 0 : void 0) != null ? _ref : window;
/*
@fn namespace
Allows you to implement a namespace of objects to the global namespace.
*/
root.namespace = function() {
var base, component, components, key, propertyName, propertyValue, separator, value, _i, _len, _ref2;
separator = ".";
base = root;
_ref2 = arguments[0];
for (key in _ref2) {
if (!__hasProp.call(_ref2, key)) continue;
value = _ref2[key];
components = key.split(separator);
if (components.length !== 1) {
for (_i = 0, _len = components.length; _i < _len; _i++) {
component = components[_i];
if (!base[component]) {
base[component] = {};
}
base = base[component];
}
} else {
base[key] = {};
base = base[key];
}
for (propertyName in value) {
if (!__hasProp.call(value, propertyName)) continue;
propertyValue = value[propertyName];
base[propertyName] = propertyValue;
}
}
return base;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment