Last active
August 18, 2016 16:53
-
-
Save mattlo/4608611 to your computer and use it in GitHub Desktop.
JavaScript Namespace Generator - Create namespaces on the fly using dot delimiters (accessible via dot notation).
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
var Namespace = (function (global) { | |
"use strict"; | |
// empty object to verify namespaced objects | |
function Namespace() {} | |
return function (namespace) { | |
var chunks = namespace.split('.'), | |
lastObjRef = global, | |
i; | |
// iterate over chunks | |
for (i = 0; i < chunks.length; ++i) { | |
if (typeof lastObjRef[chunks[i]] !== 'undefined') { | |
if (lastObjRef[chunks[i]] instanceof Namespace === true) { | |
lastObjRef = lastObjRef[chunks[i]]; | |
// next iteration | |
continue; | |
} else { | |
throw new Error("Non Namespace Object exists, cannot create namespace."); | |
} | |
} | |
// create new object | |
lastObjRef[chunks[i]] = new Namespace(); | |
// assign new last object reference | |
lastObjRef = lastObjRef[chunks[i]]; | |
} | |
// return reference to prevent double typing | |
return lastObjRef; | |
}; | |
}(this)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage:
Namespace('hello.world').Class = function () {alert('test');}
hello.world.Class();