Created
November 4, 2014 10:47
-
-
Save vkobel/59f0b185bc0c76f2cf9b to your computer and use it in GitHub Desktop.
Simple Dependency Injector in 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
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