Last active
August 29, 2015 14:11
-
-
Save zephraph/9e07e0fa82cf750f243b to your computer and use it in GitHub Desktop.
Javascript namespacing made simple
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
Namespace = function(scope, definition) { | |
var root = typeof GLOBAL !== 'undefined' ? GLOBAL : window; | |
scope = scope.split('.'); | |
for(var i = 0; i < scope.length; ++i) { | |
if(typeof root[scope[i]] === 'undefined') | |
root[scope[i]] = {}; | |
root = root[scope[i]]; | |
} | |
switch(typeof definition) { | |
case 'function': | |
definition.apply(root); | |
case 'object': | |
for(var key in definition) | |
root[key] = definition[key] | |
} | |
return root; | |
} |
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
Namespace('some.namespace', function() { | |
// 'this' is bound to the 'some.namespace' object | |
this.namespacedFunction = function() { | |
console.log('I live in some.namespace'); | |
} | |
}); | |
Namespace('some.other.namespace', { | |
// This object will be joined into the namespace | |
func: function() { | |
console.log('I live in some.other.namespace'); | |
} | |
}); | |
// The namespace can also be accessed directly | |
Namespace('some.other.other.namespace').fun = function() { | |
console.log('WEEEEEEEEEEEEEEEEEE!!!'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment