Skip to content

Instantly share code, notes, and snippets.

@r17x
Created March 14, 2019 13:36
Show Gist options
  • Select an option

  • Save r17x/98237c8edf4de6433d4b211423501342 to your computer and use it in GitHub Desktop.

Select an option

Save r17x/98237c8edf4de6433d4b211423501342 to your computer and use it in GitHub Desktop.
Dependency Injection Javascript
/**
* @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