CodeB

Blog about right code manipulation and programming.

Explanation: Dependency injection in JavaScript

f:id:BartonX:20140113173201p:plain

What is Dependency Injection? It's method to load only modules you need and I will show you how it works and why it is really awesome trick to do in JavaScript. Imagine that you write a library and you decide to create something like modules. If you use dependency injection in your library, user can load only modules he need and it will increase speed of your library and readability of code that use your library.

Dependency injection is in programming and scripting really cool feature. In JavaScript you can create magic with it. Basic support is in all major browsers so don't worry about that and you can use it everywhere. JavaScript libraries like AngularJS use it and a lot of people really don't know how it's done so in this tutorial I'll show you how you can write your small library for dependecy injection.

Now in this code you can see some AngularJS way to work with dependency injection.

As you can see AngularJS use '$' to define dependencies. And you can do your own dependencies by AngularJS services and at all it's really easy. If you register two dependencies with the same name the last one will be counted.

To be honest. There are a lot of versions for dependency injection but Angular way is the best because it's the simplest you can imagine. Here you can see RequireJS like dependency injection:

It isn't as simple as AngularJS way in this example you see that you have to put array before function and you have to follow the order that you have in the array. In AngularJS you don't have to follow any order.

Next episode: How to (in progress)