Created
September 13, 2011 13:27
-
-
Save ktonon/1213799 to your computer and use it in GitHub Desktop.
Example of a namespace function to create a hierarchy of JavaScript objects.
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
//------------------------------------------------------------- | |
// 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