Reputation: 1556
I usually create my javascript "controllers" in the following way:
var module = (function(){
function init(someService){
someService.doSomething();
}
return {
init: init
};
})();
module.init(SomeService);
I've just stumbled upon dependency injetion in javascript (e.g. JavaScript Dependency Injection).
What I would like to know is, from a testing point of view, is there any advantage using the Injector
in my link to inject mocks and such, versus simply passing them do the init
function like I do above.
To elaborate, I could just pass a SomeService
mock when I initialize my tests today. So is there any point for me to use the Injector
or something similar?
Upvotes: 2
Views: 965
Reputation: 41934
You're already doing Dependency Injection. Instead of initializing someService in the module, you're passing it into the init
method. That's exactly what Dependency Injection is about!
One of these advantages is the easiness of testing, as you can just inject a mock of someService (as you already said).
The use of an injector/dependency injection container is to manage all these dependencies. Imagine having more modules, all having their dependencies. It would soon become a nightmare to manage the initialization of all these classes.
That's were the container steps in and makes DI a joy again.
So to answer your question, if this is all the code you have, there is no point in needing an injector/container.
// the Module object
var Module = function (someService) {
this.someService = someService;
};
Module.prototype.do = function () {
this.someService.doSomething();
};
// configuring the injector
Injector.add('someService', new SomeService());
// retrieving the module instance with the SomeService being injected
var module = Injector.get(Module);
module.do();
More examples can be seen on http://www.yusufaytas.com/dependency-injection-in-javascript/
Upvotes: 4