Skip to content

Instantly share code, notes, and snippets.

@vkobel
Created November 4, 2014 10:47
Show Gist options
  • Save vkobel/59f0b185bc0c76f2cf9b to your computer and use it in GitHub Desktop.
Save vkobel/59f0b185bc0c76f2cf9b to your computer and use it in GitHub Desktop.
Simple Dependency Injector in JavaScript
var DI = function (dependency) {
this.dependency = dependency;
};
// Should return new function with resolved dependencies
DI.prototype.inject = function (func) {
var startIdx = func.toString().indexOf('(');
var endIdx = func.toString().indexOf('{');
var paramsRaw = func.toString().substr(startIdx, endIdx - startIdx).trim();
var params = paramsRaw.substr(1, paramsRaw.length -2).replace(/ /g, '').split(',');
if(params.length === 1 && params[0] == '')
params = [];
var self = this;
return function() {
if(params.length > 0){
return func.apply(this, params.map(function(itm){
return self.dependency[itm];
}));
}else{
return func();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment