Skip to content

Instantly share code, notes, and snippets.

@ktonon
Created September 13, 2011 13:27
Show Gist options
  • Save ktonon/1213799 to your computer and use it in GitHub Desktop.
Save ktonon/1213799 to your computer and use it in GitHub Desktop.
Example of a namespace function to create a hierarchy of JavaScript objects.
//-------------------------------------------------------------
// your-company.js
window.yourCompany = {
version: '1.0',
namespace: function(path) {
var part,
currentObject = window,
parts = path.split('.')
;
for (var i=0, len=parts.length; i < len; i++) {
part = parts[i];
if (!currentObject.hasOwnProperty(part)) {
currentObject[part] = {};
}
currentObject = currentObject[part];
}
return currentObject;
}
};
//-------------------------------------------------------------
// your-company/ui/wizzle.js
(function() {
var ns = yourCompany.namespace('yourCompany.ui.wizzle');
ns.defaultSize = 'tall';
})();
//-------------------------------------------------------------
// Console
console.log(yourCompany.version); // -> 1.0
console.log(yourCompany.ui.wizzle.defaultSize); // -> tall
console.log(window.ns); // -> undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment