Created
December 19, 2012 14:37
-
-
Save warseph/4337096 to your computer and use it in GitHub Desktop.
Somewhat functional javascript namespaces implementation
This file contains hidden or 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 (name) { | |
| 'use strict'; | |
| var self, namespaces, i, max; | |
| if (name.indexOf('.') >= 0) { | |
| namespaces = name.split('.'); | |
| self = this; | |
| for (i = 0, max = namespaces.length; i < max; i += 1) { | |
| self = namespace.call(self, namespaces[i]); | |
| } | |
| } else { | |
| if (this[name] === undefined) { | |
| self = function (name) { | |
| return namespace.call(self, name); | |
| }; | |
| this[name] = self; | |
| } | |
| self = this[name]; | |
| } | |
| return self; | |
| }; | |
| //Examples | |
| namespace('MyApp')('Namespace')('Test1')('Test2'); | |
| namespace('MyApp')('OtherNamespace')('Test1')('Test2'); | |
| namespace('MyApp.Just.Another.Way.To.Call.It'); | |
| //You can create a function in a namespace doing something like this: | |
| namespace('MyApp')('Namespace')('Test1')('Test2').testFunction = function () { | |
| 'use strict'; | |
| console.log('hello!'); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment