Created
March 14, 2019 13:36
-
-
Save r17x/98237c8edf4de6433d4b211423501342 to your computer and use it in GitHub Desktop.
Dependency Injection Javascript
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
| /** | |
| * @link {https://stackoverflow.com/questions/20058391/javascript-dependency-injection} | |
| */ | |
| var Injector = { | |
| dependencies: {}, | |
| add : function(qualifier, obj){ | |
| this.dependencies[qualifier] = obj; | |
| }, | |
| get : function(func){ | |
| var obj = new func; | |
| var dependencies = this.resolveDependencies(func); | |
| func.apply(obj, dependencies); | |
| return obj; | |
| }, | |
| resolveDependencies : function(func) { | |
| var args = this.getArguments(func); | |
| var dependencies = []; | |
| for ( var i = 0; i < args.length; i++) { | |
| dependencies.push(this.dependencies[args[i]]); | |
| } | |
| return dependencies; | |
| }, | |
| getArguments : function(func) { | |
| //This regex is from require.js | |
| var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; | |
| var args = func.toString().match(FN_ARGS)[1].split(','); | |
| return args; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment