Created
September 1, 2015 05:27
-
-
Save lili21/7c333f6b311724d5d245 to your computer and use it in GitHub Desktop.
dependency injection
This file contains 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 FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; | |
var FN_ARG_SPLIT = /, ?/g; | |
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; | |
var injector = { | |
store: {}, | |
register: function(key, value) { | |
this.store[key] = value; | |
}, | |
invoke: function(fn) { | |
var self = this; | |
var $inject = []; | |
if (fn.length) { | |
fnText = fn.toString().replace(STRIP_COMMENTS, ''); | |
argDecl = fnText.match(FN_ARGS)[1]; | |
args = argDecl.split(FN_ARG_SPLIT); | |
$inject = args.map(function(arg) { | |
return self.store[arg]; | |
}); | |
fn.apply(undefined, $inject); | |
} | |
} | |
}; | |
injector.register('add', function(a, b) { | |
return a + b; | |
}); | |
injector.invoke(function(add) { | |
console.log(add(3, 4)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment